Re: Using each_with_object or inject with a hash object

adithya pentela <[email protected]>
Newsgroups gmane.comp.lang.ruby.general
Message-ID <CAP4Hkiubggx=JSD6JfhHvHQKnQ8MhLBdE3vVeeoFPBfCUih=dA@mail.gmail.com>
Thanks. It makes sense. I should have looked at Hash.new documentation.

The block is yielded but the value is never assigned to the key.
{ Array.new } Vs {|h,k| h[k] = Array.new }

- Adi

On Tue, Mar 26, 2019 at 3:11 PM Brandon Weaver <[email protected]>
wrote:

> Hash.new { ¦h, k¦ h[k] = [] }
>
> This might help: https://link.medium.com/HGYloiBCnV
>
> On Tue, Mar 26, 2019, 1:03 PM adithya pentela <[email protected]>
> wrote:
>
>> Hello,
>>
>> I'm trying to use each_with_object with a hash initialized using the
>> Hash.new syntax with an implicit block.
>> I'm expecting an empty array to be initialized whenever I attempt to
>> access a new key but my results are a bit different. I looked at the
>> Enumerable documentation but could not find an answer.
>>
>> It'll be great if someone can shed some light on what is going on.
>>
>> Here's the code:
>>
>> ary = Array.new(10) { [rand(100), rand(100)] }
>> memo = Hash.new { Array.new }
>>
>>
>> ary.inject(memo) { |hsh,(i,j)| hsh[i] << j; hsh }
>>
>> >> {}
>>
>>
>> ary.each_with_object(memo) { |(i,j),hsh| hsh[i] << j }
>>
>> >> {}
>>
>>
>> ary.inject({}) { |hsh,(i,j)| hsh[i] ||= []; hsh[i] << j ; hsh }
>>
>> >> {k: [v1, v2]}
>>
>>
>> ary.each_with_object({}) { |(i,j),hsh| hsh[i] ||= []; hsh[i] << j }
>> >> {k: [v1, v2]}
>>
>>
>> Thanks,
>> Adi
>>
>>
>>
>> Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
>> <http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
>>
>
> Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
> <http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
>


Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.