I'm trying to have a hash whose value is an array.
I use the new
method with an empty array as the default value, so it was my assumption that @hash[a][0] = b
would first get an empty array (from @hash[a]
) and then assign the 0
index value to b
.
For some reason, the hash shows as empty, with size zero, even though the items can be accessed as expected. Can anyone explain why?
Another person has pointed out that it will work if I use @hash = {}
, but this requires instantiating the empty array for each key I add, which is an inconvenience, and I'm curious how the value can be accessed despite the size remaining zero.
class Test
def initialize
@hash = Hash.new []
end
def run
a = Object.new
b = Object.new
@hash[a][0] = b
puts @hash # outputs {}
puts @hash.size # outputs 0
puts @hash[a].inspect # outputs [#<Object:0x00007fe2bb80caa0>]
puts @hash[a][0].inspect # outputs #<Object:0x00007fe2bb80caa0>
end
end
test = Test.new
test.run