📜  红宝石 |反向函数

📅  最后修改于: 2022-05-13 01:55:10.796000             🧑  作者: Mango

红宝石 |反向函数

Ruby 中的 reverse函数用于将输入数组反转为另一个新数组,并使输入数组保持原样。

示例 1:

# Initializing some arrays of elements
Array1 = ["a", "b", "c", "d"]
Array2 = []
Array3 = [1]
Array4 = [1, 2]
Array5 = ["Ram", "Geeta", "Shita"]
  
# Calling to reverse function
A = Array1.reverse
B = Array2.reverse
C = Array3.reverse
D = Array4.reverse
E = Array5.reverse
  
# Printing the new reversed array
puts "#{A}"
puts "#{B}"
puts "#{C}"
puts "#{D}"
puts "#{E}"

输出:

["d", "c", "b", "a"]
[]
[1]
[2, 1]
["Shita", "Geeta", "Ram"]

示例 2:

# Initializing some arrays of elements
Array1 = ["a", "b", "c", "d"]
Array2 = []
Array3 = [1]
Array4 = [1, 2]
Array5 = ["Ram", "Geeta", "Shita"]
  
# Calling to reverse function
A = Array1.reverse
B = Array2.reverse
C = Array3.reverse
D = Array4.reverse
E = Array5.reverse
  
# Printing original input array
puts "#{Array1}"
puts "#{Array2}"
puts "#{Array3}"
puts "#{Array4}"
puts "#{Array5}"

输出:

["a", "b", "c", "d"]
[]
[1]
[1, 2]
["Ram", "Geeta", "Shita"]

注意:在上面的例子中,可以看到调用 reverse函数后,它会将原来的输入数组反转为另一个数组,并保持原来的数组不变。

参考: https://devdocs.io/ruby~2.5/array#method-i-reverse