Array # rotates the equivalent in ruby ββ1.8.7
a = [ "a", "b", "c", "d" ] a.rotate #=> ["b", "c", "d", "a"] #rotate is an Array method in Ruby 1.9. I want this functionality in Ruby 1.8.7. What is the perfect code?
If you require 'backports/1.9.2/array/rotate' , you will get Array#rotate and rotate! in earlier versions of Ruby.
In any case, you avoid reinventing the wheel, and more importantly, you get the advantage of the implementation that RubySpec goes through. It will work for all corner cases and provide compatibility with Ruby 1.9.
For example, none of the two answers is responsible for [] !
You can do the same with a.push(a.shift) . It basically removes the first element (shift) and adds it to the end (push).
Nothing like a late night party ...;)
Similar to a.rotate!(n) :
a += a.shift(n) And it works with a = [] . However, unlike a.rotate!(n) , it does nothing if n greater than the length of a .
The following saves the value of a and allows n more than a.length , due to a bit more complex:
a.last(a.length - (n % a.length)) + a.first(n % a.length) This would be best if n % a.length calculated separately, and the whole thing wrapped in a monkey method patched in Array .
class Array def rot(n) m = n % self.length self.last(self.length - m) + self.first(m) end end For rotation! version without parameter, gnab is good. If you want non-destructive, with an optional parameter:
class Array def rotate n = 1; self[n..-1]+self[0...n] end end If n can be greater than the length of the array:
class Array def rotate n = 1; return self if empty?; n %= length; self[n..-1]+self[0...n] end end