Re: Using each_with_object or inject with a hash object
Brandon Weaver <[email protected]>
| Newsgroups | gmane.comp.lang.ruby.general |
|---|---|
| Message-ID | <CAH7vphTa1vj35_XjFXhdYduan_t4rmDn8dKx275n8Y3dMSYH2Q@mail.gmail.com> |
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>