From: "David A. Black" Date: 2009-09-16T03:53:25+09:00 Subject: Re: .map.with_object(3){|v|v+3} #=> 3 Is this a bug? Hi -- On Wed, 16 Sep 2009, 7stud -- wrote: > David A. Black wrote: >> Hi -- >> >> On Tue, 15 Sep 2009, 7stud -- wrote: >> >>> ------------------------------------------------- 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 >>> > > > Thanks for the response. > > In the definition: > >> e.with_object(obj) {|(*args), memo_obj| ... } > > 1) Why *args? > > 2) Why (*args) ? I read it as just shorthand for "miscellaneous other arguments". I don't know whether there's a better way to denote that. > In the definition: > >> e.with_object(obj) {|(*args), memo_obj| ... } > > 3) Why 'memo_obj' and not 'obj'? > > Even though two different variable names makes it hard to track what is > going on, the following assignment takes place: > > memo_obj = obj I think it's schematic. obj is not necessarily the variable "obj"; it's just an object: e.with_object() while memo_obj indicates that the last parameter will bind to that object (and could serve as a variable name). 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)