红宝石 |逆转!函数
相反! Ruby 中的函数用于将输入数组反转为相同的数组。
Syntax: Array.reverse!
Here Array is the input array whose elements are to be reversed.
Parameters: This function does not accept any parameters.
Returns: the same input array with reversed element.
示例 1:
Ruby
# Initializing some arrays of elements
Array1 = ["a", "b", "c", "d"]
Array2 = []
Array3 = [1]
Array4 = [1, 2]
Array5 = ["Ram", "Geeta", "Shita"]
# Calling reverse! function
A = Array1.reverse!
B = Array2.reverse!
C = Array3.reverse!
D = Array4.reverse!
E = Array5.reverse!
# Printing the same input array
# with reversed elements
puts "#{A}"
puts "#{B}"
puts "#{C}"
puts "#{D}"
puts "#{E}"
javascript
# Initializing some arrays of elements
Array1 = ["a", "b", "c", "d"]
Array2 = []
Array3 = [1]
Array4 = [1, 2]
Array5 = ["Ram", "Geeta", "Shita"]
# Calling reverse! function
A = Array1.reverse!
B = Array2.reverse!
C = Array3.reverse!
D = Array4.reverse!
E = Array5.reverse!
# Printing original input array
# after calling reverse! function
puts "#{Array1}"
puts "#{Array2}"
puts "#{Array3}"
puts "#{Array4}"
puts "#{Array5}"
输出:
["d", "c", "b", "a"]
[]
[1]
[2, 1]
["Shita", "Geeta", "Ram"]
示例 2:
javascript
# Initializing some arrays of elements
Array1 = ["a", "b", "c", "d"]
Array2 = []
Array3 = [1]
Array4 = [1, 2]
Array5 = ["Ram", "Geeta", "Shita"]
# Calling reverse! function
A = Array1.reverse!
B = Array2.reverse!
C = Array3.reverse!
D = Array4.reverse!
E = Array5.reverse!
# Printing original input array
# after calling reverse! function
puts "#{Array1}"
puts "#{Array2}"
puts "#{Array3}"
puts "#{Array4}"
puts "#{Array5}"
输出:
["d", "c", "b", "a"]
[]
[1]
[2, 1]
["Shita", "Geeta", "Ram"]
注意:反转和反转的区别!功能是反向函数将输入数组元素反转为另一个数组并保持输入数组原样,但相反!函数将输入数组反转为相同的输入数组。
参考: https://devdocs.io/ruby~2.5/array#method-i-reverse-21