each_with_object(p1) public

Iterates the given block for each element with an arbitrary object given, and returns the initially given object.

If no block is given, returns an enumerator.

e.g.:

evens = (1..10).each_with_object([]) {|i, a| a << i*2 }
#=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Show source
Register or log in to add new notes.
July 23, 2012
2 thanks

Long-wanted functional extension

This is pretty nice method allowing you to build stuff in a functional way.

Lets say you want to build a hash from an array, keyed by array object, where each value is the number of same objects in the array.

# imperative style :-P

h = Hash.new(0)
[1, 3, 2, 3, 1, 3].each { |i| h[i] += 1 }
h # => {1=>2, 3=>3, 2=>1} 

# functional style, using inject. Note that you need to explicitly return the accumulator in the end

[1, 3, 2, 3, 1, 3].inject(Hash.new(0)) { |a, i| a[i] += 1; a } 
# => {1=>2, 3=>3, 2=>1} 

# using each_with_object. Note the reversed block params - accumulator is the last parameter. 
# Mnemonic: consistent with each_with_index, where object is the first parameter

[1, 3, 2, 3, 1, 3].each_with_object(Hash.new(0)) {|i, a| a[i] += 1}
# => {1=>2, 3=>3, 2=>1}