Allister
Allister

Reputation: 851

Changing Array Starting Point in Ruby

I currently have an array in Ruby made up of 12 elements like so:

[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100 ]

Each array element corresponds to the month of the year, so 0 is January while 11 is December.

So far so good, but now I want to change the starting month, rather than January I need to change the starting point of the array, to lets say March (2) while maintaining the values.

How would I go about re sorting the array starting point in Ruby?

Thanks for any help!

Upvotes: 0

Views: 84

Answers (1)

August
August

Reputation: 12558

You can use Array#rotate

For example:

a = (0..12).to_a # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
a.rotate(2)      # => [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1]

Upvotes: 4

Related Questions