顾名思义,reverse!函数用于反转数组的元素。大多数情况下,我们需要反转一个数组,但如果我们借助循环来实现,程序将变得相当冗长和耗时。Ruby为你提供了逆向便利!函数,该函数生成数组的倒数。不像,Ruby中的reverse函数,reverse!在原始数组本身中生成更改。它还返回数组的相反值,该数组可以存储在相应的新数组中,以完成将来的操作。
语法:
Array_name.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"] # 调用reverse! 函数 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! 函数是否在原始数组中产生更改。
范例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"] #调用 reverse! 函数 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}"
输出结果
["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!函数会在原始数组中产生更改,并借助“ puts”语句来打印数组。