Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/antlr3/test/core-extensions.rb

Instance Method Summary collapse

Instance Method Details

#pad(len, val = nil) ⇒ Object

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

243
244
245
246
247
248
249
250
# 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) ⇒ Object

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

260
261
262
263
264
265
266
267
# 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