Consider this code:
h = Hash.new(0) # New hash pairs will by default have 0 as values
h[1] += 1 #=> {1=>1}
h[2] += 2 #=> {2=>2}
That’s all fine, but:
h = Hash.new([]) # Empty array as default value
h[1] <<= 1 #=> {1=>[1]} ← Ok
h[2] <<= 2 #=> {1=>[1,2], 2=>[1,2]} ← Why did `1` change?
h[3] << 3 #=> {1=>[1,2,3], 2=>[1,2,3]} ← Where is `3`?
At this point I expect the hash to be:
{1=>[1], 2=>[2], 3=>[3]}
but it’s far from that. What is happening and how can I get the behavior I expect?
First, note that this behavior applies to any default value that is subsequently mutated (e.g. hashes and strings), not just arrays.
TL;DR: Use
Hash.new { |h, k| h[k] = [] }
if you want the most idiomatic solution and don’t care why.What doesn’t work
Why
Hash.new([])
doesn’t workLet’s look more in-depth at why
Hash.new([])
doesn’t work:We can see that our default object is being reused and mutated (this is because it is passed as the one and only default value, the hash has no way of getting a fresh, new default value), but why are there no keys or values in the array, despite
h[1]
still giving us a value? Here’s a hint:The array returned by each
[]
call is just the default value, which we’ve been mutating all this time so now contains our new values. Since<<
doesn’t assign to the hash (there can never be assignment in Ruby without an=
present†), we’ve never put anything into our actual hash. Instead we have to use<<=
(which is to<<
as+=
is to+
):This is the same as:
Why
Hash.new { [] }
doesn’t workUsing
Hash.new { [] }
solves the problem of reusing and mutating the original default value (as the block given is called each time, returning a new array), but not the assignment problem:What does work
The assignment way
If we remember to always use
<<=
, thenHash.new { [] }
is a viable solution, but it’s a bit odd and non-idiomatic (I’ve never seen<<=
used in the wild). It’s also prone to subtle bugs if<<
is inadvertently used.The mutable way
The documentation for
Hash.new
states (emphasis my own):So we must store the default value in the hash from within the block if we wish to use
<<
instead of<<=
:This effectively moves the assignment from our individual calls (which would use
<<=
) to the block passed toHash.new
, removing the burden of unexpected behavior when using<<
.Note that there is one functional difference between this method and the others: this way assigns the default value upon reading (as the assignment always happens inside the block). For example:
The immutable way
You may be wondering why
Hash.new([])
doesn’t work whileHash.new(0)
works just fine. The key is that Numerics in Ruby are immutable, so we naturally never end up mutating them in-place. If we treated our default value as immutable, we could useHash.new([])
just fine too:However, note that
([].freeze + [].freeze).frozen? == false
. So, if you want to ensure that the immutability is preserved throughout, then you must take care to re-freeze the new object.Conclusion
Of all the ways, I personally prefer “the immutable way”—immutability generally makes reasoning about things much simpler. It is, after all, the only method that has no possibility of hidden or subtle unexpected behavior. However, the most common and idiomatic way is “the mutable way”.
As a final aside, this behavior of Hash default values is noted in Ruby Koans.
† This isn’t strictly true, methods like
instance_variable_set
bypass this, but they must exist for metaprogramming since the l-value in=
cannot be dynamic.When you write,
you pass default reference of array to all elements in hash. because of that all elements in hash refers same array.
if you want each element in hash refer to separate array, you should use
for more detail of how it works in ruby please go through this: http://ruby-doc.org/core-2.2.0/Array.html#method-c-new
You're specifying that the default value for the hash is a reference to that particular (initially empty) array.
I think you want:
That sets the default value for each key to a new array.
The operator
+=
when applied to those hashes work as expected.This may be because
foo[bar]+=baz
is syntactic sugar forfoo[bar]=foo[bar]+baz
whenfoo[bar]
on the right hand of=
is evaluated it returns the default value object and the+
operator will not change it. The left hand is syntactic sugar for the[]=
method which won't change the default value.Note that this doesn't apply to
foo[bar]<<=baz
as it'll be equivalent tofoo[bar]=foo[bar]<<baz
and<<
will change the default value.Also, I found no difference between
Hash.new{[]}
andHash.new{|hash, key| hash[key]=[];}
. At least on ruby 2.1.2 .