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

Категории