Array#rotate equivalent in ruby 1.8.7

前端 未结 4 918
南笙
南笙 2021-01-13 00:55
a = [ \"a\", \"b\", \"c\", \"d\" ]
a.rotate         #=> [\"b\", \"c\", \"d\", \"a\"]

#rotate is a method of Array in R

4条回答
  •  生来不讨喜
    2021-01-13 01:32

    For the rotate! version without the parameter, gnab's is good. If you want the non-destructive one, with an optional parameter:

    class Array
      def rotate n = 1; self[n..-1]+self[0...n] end
    end
    

    If n may become larger 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
    

提交回复
热议问题