Sha256: 62e787666472b2d330b2b0810210a1dd383d21c2af40f5b690629c75ea480e27

Contents?: true

Size: 1.23 KB

Versions: 26

Compression:

Stored size: 1.23 KB

Contents

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

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
facets-1.0.0 lib/facet/array/rotate.rb
facets-0.9.0 lib/nano/array/rotate.rb
facets-1.0.3 packages/core/lib/facet/array/rotate.rb
facets-1.2.1 lib/facets/core/array/rotate.rb
facets-1.2.0 lib/facets/core/array/rotate.rb
facets-1.3.0 lib/facets/core/array/rotate.rb
facets-1.1.0 lib/facet/array/rotate.rb
facets-1.3.1 lib/facets/core/array/rotate.rb
facets-1.3.3 lib/facets/core/array/rotate.rb
facets-1.3.2 lib/facets/core/array/rotate.rb
facets-1.4.0 lib/facets/core/array/rotate.rb
facets-1.4.2 lib/facets/core/array/rotate.rb
facets-1.4.1 lib/facets/core/array/rotate.rb
facets-1.4.3 lib/facets/core/array/rotate.rb
facets-1.4.5 lib/facets/core/array/rotate.rb
facets-1.4.4 lib/facets/core/array/rotate.rb
facets-1.7.30 lib/facets/core/array/rotate.rb
facets-1.7.0 lib/facets/core/array/rotate.rb
facets-1.7.38 lib/facets/core/array/rotate.rb
facets-1.7.46 lib/facets/core/array/rotate.rb