From: "David A. Black" Date: 2009-09-15T11:33:29+09:00 Subject: Re: .map.with_object(3){|v|v+3} #=> 3 Is this a bug? Hi -- On Tue, 15 Sep 2009, 7stud -- wrote: > David Masover wrote: >> On Sunday 13 September 2009 09:19:31 pm ErMaker wrote: >>> => [4, 5, 6] >> That makes sense, now that I know what with_object does. >> > > Could you enlighten me? The following doesn't yield any clues: > > $ri19 Enumerator#with_object > > ------------------------------------------------- Enumerator#with_object > e.with_object(obj) {|(*args), memo_obj| ... } > e.with_object(obj) > > From Ruby 1.9.1 > ------------------------------------------------------------------------ > 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. That's pretty much what it does. It's kind of like inject, except it uses the same object each time through instead of assigning the accumulator slot to the value of the block. Thus: array = [1,2,3,4,5] tens_hash = array.each_with_object({}) {|n,obj| obj[n] = n * 10 } # => {1=>10, 2=>20, 3=>30, 4=>40, 5=>50} It saves you having to do that awkward: {|h,n| h[n] = n * 10; h } thing to feed the object back into the loop. Without a block, it returns an enumerator, which will then do a "with"-style double iteration (like with_index) based on whatever you call on it: >> array = [1,2,3,4,5] => [1, 2, 3, 4, 5] >> enum = array.each_with_object({}) => # >> tens_hash = enum.each {|n,obj| obj[n] = n * 10 } => {1=>10, 2=>20, 3=>30, 4=>40, 5=>50} David -- David A. Black, Director Ruby Power and Light, LLC (http://www.rubypal.com) Ruby/Rails training, consulting, mentoring, code review Book: The Well-Grounded Rubyist (http://www.manning.com/black2)