Notes posted by EdvardM
RSS feed
1 thank
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}


