method
each_with_object
v2_2_9 -
Show latest stable
-
1 note -
Class: Enumerable
- 1_8_6_287
- 1_8_7_72
- 1_8_7_330
- 1_9_1_378 (0)
- 1_9_2_180 (-8)
- 1_9_3_125 (0)
- 1_9_3_392 (0)
- 2_1_10 (-38)
- 2_2_9 (0)
- 2_4_6 (0)
- 2_5_5 (0)
- 2_6_3 (0)
- What's this?
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.
evens = (1..10).each_with_object([]) { |i, a| a << i*2 } #=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Register or
log in
to add new notes.
EdvardM -
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}