Sha256: 1573cdd7899548dd6f9d48b13ae9481a63ff21b8b1d740edbb6240d1cba247ad

Contents?: true

Size: 1.56 KB

Versions: 10

Compression:

Stored size: 1.56 KB

Contents

# = Array Padding Extensions
#
# Padding extensions for Array.

#
class Array

  # CREDIT Richard Laugesen

  # Pad an array with a given <tt>value</tt> upto a given <tt>length</tt>.
  #
  #   [0,1,2].pad(6,"a")  #=> [0,1,2,"a","a","a"]
  #
  # If <tt>length</tt> is a negative number padding will be added
  # to the beginning of the array.
  #
  #   [0,1,2].pad(-6,"a")  #=> ["a","a","a",0,1,2]

  def pad(len, val=nil)
    return dup if self.size >= len.abs
    if len < 0
      Array.new((len+size).abs,val) + self
    else
      self + Array.new(len-size,val)
    end
  end

  # Like #pad but changes the array in place.
  #
  #    a = [0,1,2]
  #    a.pad!(6,"x")
  #    a  #=> [0,1,2,"x","x","x"]

  def pad!(len, val=nil)
    return self if self.size >= len.abs
    if len < 0
      replace Array.new((len+size).abs,val) + self
    else
      concat Array.new(len-size,val)
    end
  end

end



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

  require 'test/unit'

  class TestArray < Test::Unit::TestCase

    def test_pad
      r = [0,1,2,3].pad(7,"x")
      x = [0,1,2,3,"x","x","x"]
      assert_equal(x,r)
    end

    def test_pad!
      a = [0,1,2,3]
      r = a.pad!(6,"y")
      x = [0,1,2,3,"y","y"]
      assert_equal(x,a)
    end

    def test_pad_negative
      r = [0,1,2,3].pad(-7,"n")
      x = ["n","n","n",0,1,2,3]
      assert_equal(x,r)
    end

    def test_pad_negative!
      a = [0,1,2,3]
      r = a.pad!(-6,"q")
      x = ["q","q",0,1,2,3]
      assert_equal(x,a)
    end

  end

=end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
facets-2.0.1 lib/core/facets/array/pad.rb
facets-2.0.0 lib/core/facets/array/pad.rb
facets-2.0.2 lib/core/facets/array/pad.rb
facets-2.0.4 lib/core/facets/array/pad.rb
facets-2.0.5 lib/core/facets/array/pad.rb
facets-2.1.1 lib/core/facets/array/pad.rb
facets-2.1.2 lib/core/facets/array/pad.rb
facets-2.1.0 lib/core/facets/array/pad.rb
facets-2.0.3 lib/core/facets/array/pad.rb
facets-2.1.3 lib/core/facets/array/pad.rb