1. Home
  2. Computing & Technology
  3. Ruby

How Can I Rotate an Array in Ruby?

By , About.com Guide

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
More Ruby Q&A
Explore Ruby
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Ruby
  4. Tasks & Scripts
  5. FAQs
  6. How Can I Rotate an Array in Ruby?

©2010 About.com, a part of The New York Times Company.

All rights reserved.