Our Daily Method #5: Enumerable#inject!

Geplaatst door Michiel de Mare ma, 11 feb 2008 07:20:00 GMT

Enumerable#inject is a terrific and flexible method – so flexible that I regularly abuse it:

Take for instance this fragment:


arr_of_arr.inject(Hash.new(0)) do |h,a|
  a.each {|x| h[x] += 1 }
  h
end

# I could simply use a local variable
h = Hash.new(0)
ar_of_ar.each do |h,a|
  a.each {|x| h[x] += 1 }
end

# Ruby 1.9 offers Object#tap
Hash.new(0).tap do |h|
  ar_of_ar.each do |a|
    a.each {|x| h[x] += 1 }
  end
end

And yet I like my inject-solution better – no local variables or superfluous blocks. Why not change inject by not returning the value of the block and using it in the next iteration, why not each time pass in the argument to inject. Let’s name this function inject!


module Enumerable
  def inject!(memo)
    each {|x| yield(memo,x) }
    memo
  end
end

ar_of_ar.inject!(Hash.new(0)){|h,a| a.each{|x| h[x] += 1}}

Geplaatst in , ,  | geen reacties

Reacties

(Laat url/e-mail achter »)

   Voorvertoning