顾名思义,在ruby中,reverse函数用于反转数组,但要稍加扭转,它将反转数组并将其存储到新数组中。反向函数对原始数组不起作用。通过此功能,无论数组的顺序如何,该顺序都可以颠倒。
reverse 函数不允许任何参数。它的返回类型是一个数组,显然,返回的数组与实际数组相反。
语法:
new_array = old_array.reverse
现在,让我们借助示例更广泛地了解反向函数的实现。
范例1:
=begin Ruby program to demonstrate implementation of reverse function =end #初始化一些元素数组 Arr1 = ["apple", "mango", "banana", "apricot", "plum", "cherry"] Arr2 = ["one","two", "three", "four", "five"] Arr3 = [10,20] Arr4 = [110, 210, 310, 410, 510] Arr5 = ["C++", "Java", "C#", "Visual Basic", "Perl", "Python"] Arr6 = ["Hrithik", "Satyam", "Amisha", "Kajal", "Wamp"] #调用函数 NewArr1 = Arr1.reverse NewArr2 = Arr2.reverse NewArr3 = Arr3.reverse NewArr4 = Arr4.reverse NewArr5 = Arr5.reverse NewArr6 = Arr6.reverse #打印新的反向数组 puts "#{NewArr1}" puts "#{NewArr2}" puts "#{NewArr3}" puts "#{NewArr4}" puts "#{NewArr5}" puts "#{NewArr6}"
输出结果
["cherry", "plum", "apricot", "banana", "mango", "apple"] ["five", "four", "three", "two", "one"] [20, 10] [510, 410, 310, 210, 110] ["Python", "Perl", "Visual Basic", "C#", "Java", "C++"] ["Wamp", "Kajal", "Amisha", "Satyam", "Hrithik"]
在上面的示例中,您可以观察到我们已经初始化了六个数组,然后在新数组中调用了反向函数。reverse函数以相反的顺序返回数组,并将值存储在新的对应数组中。
现在,让我们通过参考下面给出的示例来查找由reverse函数所做的更改是否反映在原始数组中,
范例2:
=begin Ruby program to demonstrate implementation of reverse function =end # 初始化元素数组 Arr1 = ["apple", "mango", "banana", "apricot", "plum", "cherry"] Arr2 = ["one","two", "three", "four", "five"] Arr3 = [10,20] Arr4 = [110, 210, 310, 410, 510] Arr5 = ["C++", "Java", "C#", "Visual Basic", "Perl", "Python"] Arr6 = ["Hrithik", "Satyam", "Amisha", "Kajal", "Wamp"] # 调用反向函数 NewArr1 = Arr1.reverse NewArr2 = Arr2.reverse NewArr3 = Arr3.reverse NewArr4 = Arr4.reverse NewArr5 = Arr5.reverse NewArr6 = Arr6.reverse # 打印原始数组 puts "#{Arr1}" puts "#{Arr2}" puts "#{Arr3}" puts "#{Arr4}" puts "#{Arr5}" puts "#{Arr6}"
输出结果
["apple", "mango", "banana", "apricot", "plum", "cherry"] ["one", "two", "three", "four", "five"] [10, 20] [110, 210, 310, 410, 510] ["C++", "Java", "C#", "Visual Basic", "Perl", "Python"] ["Hrithik", "Satyam", "Amisha", "Kajal", "Wamp"]
您可以观察到两个输出之间的差异。借助示例,实践证明了reverse函数不会影响原始数组。