Module: MoreCoreExtensions::ArrayStretch

Defined in:
lib/more_core_extensions/core_ext/array/stretch.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#stretch(*arys) ⇒ Object

Stretch receiver to be the same size as the longest argument Array.

[1, 2].stretch([3, 4], [5, 6, 7])  #=> [1, 2, nil]


24
25
26
# File 'lib/more_core_extensions/core_ext/array/stretch.rb', line 24

def stretch(*arys)
  self.dup.stretch!(*arys)
end

#stretch!(*arys) ⇒ Object

Stretch receiver to be the same size as the longest argument Array. Modifies the receiver in place.

[1, 2].stretch!([3, 4], [5, 6, 7])  #=> [1, 2, nil]


31
32
33
34
35
# File 'lib/more_core_extensions/core_ext/array/stretch.rb', line 31

def stretch!(*arys)
  max_size = (arys + [self]).collect { |a| a.length }.max
  self[max_size - 1] = nil unless self.length == max_size
  return self
end

#zip_stretched(*arys) ⇒ Object

Zip arguments stretching the receiver if necessary. Ruby’s zip method will only zip up to the number of the receiver’s elements if the receiver is shorter than the argument Arrays. This method will zip nils instead of stopping.

[1, 2].zip([3, 4], [5, 6, 7])  #=> [[1, 3, 5], [2, 4, 6]]
[1, 2].zip_stretched([3, 4], [5, 6, 7])  #=> [[1, 3, 5], [2, 4, 6], [nil, nil, 7]


44
45
46
# File 'lib/more_core_extensions/core_ext/array/stretch.rb', line 44

def zip_stretched(*arys)
  self.stretch(*arys).zip(*arys)
end