class Array

Public Instance Methods

pad( len, val=nil ) click to toggle source

Pad an array with a given value upto a given length.

[0,1,2].pad(6,"a")  #=> [0,1,2,"a","a","a"]

If length 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]

CREDIT: Richard Laugesen
# File lib/antlr3/test/core-extensions.rb, line 243
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
pad!( len, val=nil ) click to toggle source

Like pad but changes the array in place.

  a = [0,1,2]
  a.pad!(6,"x")
  a  #=> [0,1,2,"x","x","x"]

CREDIT: Richard Laugesen
# File lib/antlr3/test/core-extensions.rb, line 260
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