instance method each_with_object

Ruby on Rails 2.3.18

Since v2.2.3 Last seen in v3.2.22.5

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5

Signature

each_with_object(memo, &block)

Iterates over a collection, passing the current element and the memo to the block. Handy for building up hashes or reducing collections down to one object. Examples:

%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } #=> {'foo' => 'FOO', 'bar' => 'BAR'}

Note that you can’t use immutable objects like numbers, true or false as the memo. You would think the following returns 120, but since the memo is never changed, it does not.

(1..5).each_with_object(1) { |value, memo| memo *= value } # => 1

Parameters

memo req
block block
Source
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 77
  def each_with_object(memo, &block)
    memo.tap do |m|
      each do |element|
        block.call(element, m)
      end
    end
  end

Defined in activesupport/lib/active_support/core_ext/enumerable.rb line 77 · View on GitHub · Improve this page · Find usages on GitHub

Defined in Enumerable

Type at least 2 characters to search.

↑↓ navigate · open · esc close