Ruby 中的数组 reverse() 与 reverse!


在本文中,我们将探讨 Ruby 中用于数组的两种最常用的方法。它们是 reverse() 方法和 reverse! 方法。

reverse() 方法

Ruby 中的 reverse() 方法会颠倒数组的内容并返回一个新数组。现在,我们来看几个示例以了解它是如何工作的。

示例 1

# reverse() method in Ruby

# array declaration
first_arr = [18, 22, 33, nil, 7, 6]

# array declaration
second_arr = [1, 5, 1, 3, 88, 9]

# array declaration
third_arr = [18, 22, 55, 6]

# reverse method example
puts "reversed array : #{first_arr.reverse()}

" puts "reversed array : #{second_arr.reverse()}

" puts "reversed array : #{third_arr.reverse()}

"

输出

reversed array : [6, 7, nil, 33, 22, 18]
reversed array : [9, 88, 3, 1, 5, 1]
reversed array : [6, 55, 22, 18]

示例 2

我们再来看一个相同的 reverse 方法的示例。

# reverse() method in Ruby

# array declaration
first_arr = ["abc", "nil", "dog"]

# array declaration
second_arr = ["buffalo", nil]

# array declaration
third_arr = ["snake", nil, "dog"]

# reverse method example
puts "reversed array : #{first_arr.reverse()}

" puts "reversed array : #{second_arr.reverse()}

" puts "reversed array : #{third_arr.reverse()}

"

输出

reversed array : ["dog", "nil", "abc"]
reversed array : [nil, "buffalo"]
reversed array : ["dog", nil, "snake"]

reverse! 函数

当我们希望将输入数组的内容颠倒到同一数组中时,会使用 reverse! 函数。我们来看 reverse! 函数的一个示例。

示例 3

# arrays of elements
arr1 = ["a", "b", "c", "d"]
arr2 = []
arr3 = [1]
arr4 = ["Javed", "Raju","Pruthvi"]

# reverse!
A = arr1.reverse!
B = arr2.reverse!
C = arr3.reverse!
D = arr4.reverse!

# Printing the same input array
# with reversed elements
puts "#{A}"
puts "#{B}"
puts "#{C}"
puts "#{D}"

输出

["d", "c", "b", "a"]
[]
[1]
["Pruthvi", "Raju", "Javed"]

更新日期:2022-01-25

783 次浏览

开启你的职业生涯

完成课程即可获得认证

开始
广告