reverse an array in ruby

To reverse an array in ruby, you can use either the .reverse or .reverse! method.

.reverse returns a new array with elements in reverse order:

main.rb
my_array = [1,2,3,4,5]
reversed_array = my_array.reverse #=> [5,4,3,2,1]
73 chars
3 lines

.reverse! reverses the elements in place, modifying the original array:

main.rb
my_array.reverse! #=> [5,4,3,2,1]
34 chars
2 lines

If you want a non-destructive way to reverse an array, use .reverse instead.

gistlibby LogSnag