I am new to Ruby and running Ruby Koans. In Ruby Koans, in about_hashes.rb file, there is an example of assigning default value to a hash.
hash = Hash.new([])
hash[:one] << "uno"
hash[:two] << "dos"
puts hash[:one] # this is ["uno", "dos"]
here both hash[:one]
& hash[:two]
or any key like hash[:three]
(non existing key) all have the value ["uno", and "dos"] I did not understand how "<<" is used here. Also, when I tried extracting keys & values of the hash, or print the keys/values, it is empty.
puts (hash.values.size) # size is 0 here
puts (hash.keys.size) # size is 0
puts hash.values # nothing gets printed
puts hash.keys #nothing gets printed.
So what is happening here? Where are the values getting stored, if they are not getting stored in the hash as keys or values.
in the next example, when Hash is defined as
hash = Hash.new {|hash, key| hash[key] = [] }
hash[:one] << "uno"
hash[:two] << "dos"
puts hash[:one] #this is "uno"
puts hash[:two] #this is "dos"
puts hash[:three] # this is undefined.
I guess in the second example, hash is initializing all the keys with a blank array. So "uno" is getting appended to the empty array when "<<" this operator is used? I am confused about both the examples. I don't know what is happening in both of them. I couldn't find much information on this example in google as well. If somebody can help me explain these 2 examples it will be helpful. Thanks in advance