So I was looking for this in the ruby standard library and didn’t find it. So I rolled my own :) Enjoy!
class Array
def rotate n=1 #positive right, negative left
a = self.dup
(n % self.size).times{ a = [ a.pop ] + a }
a
end
def rotate! n=1
replace rotate(n)
end
end
Addendum:
I found another way to do this at ruby quiz
...
num.times{ a << a.shift }
...

Leave a Reply