Ruby Hash of Arrays outputting {}

If I do the following:

h = Hash.new(Array.new)
h['a'].push('apple')

puts h['a']
puts h 

I get the following output:

apple
{}

I do not understand why put h does not output:

{"a"=>["apple"]}

Any help is much appreciated ...

+4
source share
1 answer

Read it

new (obj) → new_hash

If specified obj, this single object will be used for all default values.

Hash.new(Array.new)- on this line you created the default array object. Which will be returned whenever you want to access a key that does not exist inside the hash.

h['a'].push('apple') - / , . h['a'] , Array.new, Array#push, all.Thus h['a'] . puts h {}, 'a' .

. :

h = Hash.new(Array.new)
h.default # => []
h['a'].push('apple')
h.default # => ["apple"]

:

#adding a key
h['a'] = 'Bob'
h['a'] # => "Bob"
h # => {"a"=>"Bob"}
#again default vaule as you are trying to aceess a non-exist key
h['b'] # => ["apple"]

Hash#[]

Reference - , . , ( . Hash::new).

+13

Source: https://habr.com/ru/post/1540277/


All Articles