Sha256: 252453456330fe05130b91f8d5a4713bf6fd53dd56f2e30fa9e980e5d2d5948a

Contents?: true

Size: 717 Bytes

Versions: 11

Compression:

Stored size: 717 Bytes

Contents

class Array

  # Zip <tt>self</tt> with <tt>other</tt>, combining the elements
  # with the provided block or symbol.
  # The resulting array will be as long as the shorter of
  # the two arrays.
  #   [1,2,3].zip_with([6,5,4], :+)
  #   #=> [7, 7, 7]
  #   %w(a b).zip_with(%w(c d), :+)
  #   #=> ["ac", "bd"]
  #
  # For more complex combinations, a block can be provided:
  #
  #   [1,2,3].zip_with([6,5,4]) { |a,b| 3*a+2*b }
  #   #=> [15, 16, 17]
  def zip_with(other, op=nil)
    return [] if self.empty? || other.empty?
    clipped = self[0..other.length-1]
    zipped = clipped.zip(other)

    if op
      zipped.map { |a, b| a.send(op, b) }
    else
      zipped.map { |a, b| yield(a, b) }
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
shenanigans-1.0.13 lib/shenanigans/array/zip_with.rb
shenanigans-1.0.11 lib/shenanigans/array/zip_with.rb
shenanigans-1.0.10 lib/shenanigans/array/zip_with.rb
shenanigans-1.0.9 lib/shenanigans/array/zip_with.rb
shenanigans-1.0.8 lib/shenanigans/array/zip_with.rb
shenanigans-1.0.7 lib/shenanigans/array/zip_with.rb
shenanigans-1.0.6 lib/shenanigans/array/zip_with.rb
shenanigans-1.0.5 lib/shenanigans/array/zip_with.rb
shenanigans-1.0.4 lib/shenanigans/array/zip_with.rb
shenanigans-1.0.3 lib/shenanigans/array/zip_with.rb
shenanigans-1.0.2 lib/shenanigans/array/zip_with.rb