"If a block is specified, it will be called with the hash object and
the key, and should return the default value. It is the block‘s
responsibility to store the value in the hash if required."
In the first example, result[:mem] should be before "result[:mem] << i" is
executed. Afterwards it should be [1], and the return value should be {:mem =>
[1]}.
In the second example, what does "<<=" stand for?
Roy
···
On Mon, Apr 25, 2011 at 08:50:13PM +0900, Roger Braun wrote:
Hi Aaron
2011/4/25 Aaron <aaron2ti@gmail.com>:
> see the following codes pls, I wonder if this's a intent or a bug. For me the first line sounds better having same result with the later line
>
>>> [1].inject(Hash.new {}){ |result, i| result[:mem] << i; result }
> => {}
>>> [1].inject(Hash.new {}){ |result, i| result[:mem] <<= i; result }
> => {:mem=>[1]}
"If a block is specified, it will be called with the hash object and
the key, and should return the default value. It is the block‘s
responsibility to store the value in the hash if required."
The non-block form makes a single array the default for all keys. The resulting hash still has no entries, but if you ask for any key that doesn't exist, you'll get the (one) default value back. That default value is a true object that is modified by the << each time the inject block is executed.