Reversing an Array






Reversing an Array

Problem

Your array is the wrong way around: the last item should be first and the first should be last.

Solution

Use reverse to create a new array with the items reversed. Internal subarrays will not themselves be reversed.

	[1,2,3].reverse                           # => [3, 2, 1]
	[1,[2,3,4],5].reverse                     # => [5, [2, 3, 4], 1]

Discussion

Like many operations on basic Ruby types, reverse has a corresponding method, reverse!, which reverses an array in place:

	a = [1,2,3]
	a. 
reverse!
	a                                       # => [3, 2, 1]

Don't reverse an array if you just need to iterate over it backwards. Don't use a for loop either; the reverse_each iterator is more idiomatic.

See Also

  • Recipe 1.4, " Reversing a String by Words or Characters"

  • Recipe 4.1, "Iterating Over an Array," talks about using Array#reverse_each to iterate over an array in reverse order

  • Recipe 4.2, "Rearranging Values Without Using Temporary Variables"



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows