
class Array

  # Rotates an array's elements from back to front n times.
  #
  #   [1,2,3].rotate      #=> [3,1,2]
  #   [3,1,2].rotate      #=> [2,3,1]
  #   [3,1,2].rotate      #=> [1,2,3]
  #   [1,2,3].rotate(3)   #=> [1,2,3]
  #
  # A negative parameter reverses the order from front to back.
  #
  #   [1,2,3].rotate(-1)  #=> [2,3,1]
  #
  def rotate(n=1)
    self.dup.rotate!(n)
  end

  # Same as #rotate, but acts in place.
  #
  #   a = [1,2,3]
  #   a.rotate!
  #   a  #=> [3,1,2]
  #
  def rotate!(n=1)
    n = n.to_int
    return self if (n == 0 or self.empty?)
    if n > 0
      n.abs.times{ self.unshift( self.pop ) }
    else
      n.abs.times{ self.push( self.shift ) }
    end
    self
  end

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCArray < Test::Unit::TestCase

    def test_rotate
      a = [1,2,3]
      assert_equal( [3,1,2], a.rotate, 'clockwise' )
      assert_equal( [2,3,1], a.rotate(-1), 'counter-clockwise' )
    end

    def test_rotate!
      a = [1,2,3]
      a.rotate!
      assert_equal( [3,1,2], a, 'clockwise' )
      a.rotate!(-1)
      assert_equal( [1,2,3], a, 'counter-clockwise' )
    end

  end

=end
