Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash of Arrays outputing {} [duplicate]

Tags:

ruby

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 don't understand why puts h isn't outputing:

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

Any help much appreciated...

like image 844
jx12345 Avatar asked Dec 11 '22 05:12

jx12345


1 Answers

Read this

new(obj) → new_hash

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

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

h['a'].push('apple') - By this line, you actually adding/pushing a value to that default array object,but not adding any key to the hash. h['a'] is returning you the array you defined with Array.new, on that you are calling Array#push, that's all.Thus h['a'] is giving you the current content of that default array. puts h ofcourse will give you {}, as you didn't added the key 'a' to the hash.

See the same in action :

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

Now look the code again :

#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"]

Worth to read Hash#[]

Element Reference— Retrieves the value object corresponding to the key object. If not found, returns the default value (see Hash::new for details).

like image 68
Arup Rakshit Avatar answered Mar 24 '23 07:03

Arup Rakshit