Array#rotate equivalent in ruby 1.8.7

前端 未结 4 917
南笙
南笙 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:22

    Nothing like coming way late to the party... ;)

    Similar to a.rotate!(n):

    a += a.shift(n)
    

    And it works with a = []. However, unlike a.rotate!(n), it doesn't do anything if n is greater than the length of a.

    The following preserves the value of a and allow n greater than a.length to work, at the expense of being a little more elaborate:

    a.last(a.length - (n % a.length)) + a.first(n % a.length)
    

    This would obviously be best if n % a.length is computed once separately and the whole thing wrapped in a method monkey patched into Array.

    class Array
      def rot(n)
        m = n % self.length
        self.last(self.length - m) + self.first(m)
      end
    end
    

提交回复
热议问题