Ezra Zygmuntowicz
11/10/2007 9:23:00 PM
On Nov 10, 2007, at 7:50 AM, Rick DeNatale wrote:
> On Nov 10, 2007 9:37 AM, Trans <transfire@gmail.com> wrote:
>>
>>
>> On Nov 10, 8:50 am, "Rick DeNatale" <rick.denat...@gmail.com> wrote:
>>> On 11/9/07, Trans <transf...@gmail.com> wrote:
>>>
>>>
>>>
>>>> Are these strictly equivalent? I get the feeling no, but I haven't
>>>> been able to demonstrate it yet.
>>>
>>>> def injecting(s)
>>>> inject(s) do |k, i|
>>>> yield(k, i); k
>>>> end
>>>> end
>>>
>>>> def injecting(res, &block)
>>>> ([res]*length).zip(to_a).each(&block)
>>>> res
>>>> end
>>>
>>>> Thanks,
>>>> T.
>>>
>>> I can't see how in general they can be.
>>>
>>> In which class or module are you defining these? Since you are
>>> using
>>> inject and each, I'm guessing that it's either Enumerable or some
>>> subclass,
>>>
>>> But then depending on which subclass you don't have a length
>>> method so...
>>>
>>> Perhaps some more context would help.
>>
>> Oh sorry, I meant to put that. These are Enumerable methods.
>>
> module Enumerable
> def injecting(s)
> inject(s) do |k, i|
> yield(k, i); k
> end
> end
>
> def injecting2(res, &block)
> ([res]*length).zip(to_a).each(&block)
> res
> end
> end
>
> (1..3).injecting(0) {|k,i| k + i} # => 0
> (1..3).injecting2(0) {|k,i| k + i} # =>
> # ~> -:9:in `injecting2': undefined local variable or method `length'
> for 1..3:Range (NameError)
> # ~> from -:15
>
> Which illustrates my point.
>
> Just what is injecting supposed to mean anyway? The first
> implementation uses inject and takes a two argument block like inject
> does, but seems to be going out of it's way to disregard the value of
> the argument block.
>
> This doesn't seem much like inject to me.
injecting is similar to returning in rails. There is a common pattern
of accumulating a hash via inject that looks like this:
[1,2,3].inject({}) { |memo,n| memo[n] = n ; memo}
#=> {1=>1, 3=>3,2=>2}
Note the ugly trailing ;memo, this is so the fll accumulated hash is
the final return result.
injecting is just a little bit nicer way to do the same thing:
[1,2,3].injecting({}) { |memo,n| memo[n] = n }
#=> {1=>1, 3=>3,2=>2}
Cheers-
-Ezra