1. Technology
Send to a Friend via Email
You can opt-out at any time. Please refer to our privacy policy for contact information.

How Can I Rotate an Array in Ruby?

By

Question: How Can I Rotate an Array in Ruby?
Answer:

"Rotating" an array means taking something off the front and add it to the back. Thus, rotating the array [1,2,3] would result in [2,3,1]. Ruby already provides something for taking from the front of an array (the shift method) and something for adding to the back of an array (the push method), so all you have to do is stick them together.

 irb(main):001:0> a = [1,2,3]
 => [1, 2, 3]
 irb(main):002:0> a.push a.shift
 => [2, 3, 1]
 irb(main):003:0>
 

Put these together in the Array class, and you'll be able to rotate any array easily.

 class Array
   def rotate
     push shift
   end
 end
 
Top Related Searches
  • class array
  • array class
  • ruby
  • nbsp
    1. About.com
    2. Technology
    3. Ruby
    4. Tutorials
    5. FAQs
    6. How Can I Rotate an Array in Ruby?

    ©2014 About.com. All rights reserved.