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"


Strings

Numbers

Date and Time

Arrays

Hashes

Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming

XML and HTML

Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration



Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net