Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/array_zip_with/core_ext/array.rb

Overview

Author:

Instance Method Summary collapse

Instance Method Details

#zip_with(*args, &block) ⇒ Array #zip_with(*args, operator) ⇒ Array

Overloads:

  • #zip_with(*args, &block) ⇒ Array

    Zips the input arrays with ‘self` and invokes block with the elements of the zipped array.

    Examples:

    With one input array

    a = [1, 2, 3]
    a.zip_with([3, 2, 1]) { |x, y| x + y } # => [4, 4, 4]

    With multiple input arrays

    a = [1, 2, 3]
    a.zip_with([4, 5, 6], [7, 8, 9]) do |x, y, z|
      (y - x) * z
    end # => [21, 24, 27]

    Parameters:

    • args (Array)

      One or more arrays

    Returns:

  • #zip_with(*args, operator) ⇒ Array

    Zips the input arrays with ‘self` and reduces the zipped array with the :operator

    Examples:

    With one input array

    a = [1, 2, 3]
    a.zip_with([3, 2, 1], :+) { |x, y| x + y } # => [4, 4, 4]

    With multiple input arrays

    a = [1, 2, 3]
    a.zip_with([4, 5, 6], [7, 8, 9], :+) # => [12, 15, 18]

    Parameters:

    • args (Array)

      One or more arrays

    • operator (Symbol)

      Operator to reduce the zipped array with

    Returns:

Raises:

  • (ArgumentError)

    If there is no symbol or a block as the last parameter.



30
31
32
33
34
35
36
# File 'lib/array_zip_with/core_ext/array.rb', line 30

def zip_with(*args)
  return zip(*args).map(&Proc.new) if block_given?
  operator = args.pop
  raise ArgumentError, "A block or symbol \
      must be provided" unless operator.is_a?(Symbol)
  zip(*args).map { |elems| elems.reduce(operator) }
end