Using each_with_object or inject with a hash object
adithya pentela <[email protected]>
| Newsgroups | gmane.comp.lang.ruby.general |
|---|---|
| Message-ID | <CAP4Hkiv4kLs=jVPvaVo93hSdOpid+UWxZ7AXECYT92kb2GGbyg@mail.gmail.com> |
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>