Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array#rotate equivalent in ruby 1.8.7

Tags:

ruby

a = [ "a", "b", "c", "d" ]
a.rotate         #=> ["b", "c", "d", "a"]

#rotate is a method of Array in Ruby 1.9. I want this functionality in Ruby 1.8.7. What is the ideal code?

like image 842
rubyprince Avatar asked Mar 11 '11 07:03

rubyprince


1 Answers

If you require 'backports/1.9.2/array/rotate', you will get Array#rotate and rotate! in older versions of Ruby.

Either way, you avoid reinventing the wheel, and more importantly you gain the advantage of an implementation that passes RubySpec. It will work for all corner cases and ensure compatibility with Ruby 1.9.

For example, none of the two answers given work for []!

like image 186
Marc-André Lafortune Avatar answered Nov 03 '22 09:11

Marc-André Lafortune