I am trying to insert a List in Hash.. However, hash[key].size is giving me invalid results.
p = Hash.new
p = {"a" => ["b","e"]}
puts p["a"].size #prints 2 ----This is the Problem
p["a"] << ["d", "f"]
puts p["a"].size #prints 3
puts p["a"][1] #prints e
puts p["a"][2] #prints df
How, adding more lists increment the size only by one (which is correct). Is there any way to properly initialize the hash -to not increase the size to 2.
Edited to add: Your comments indicate that you want for element ‘a’ to be an array of arrays. Here it is:
When diagnosing a problem, prefer
ptoputs.putscan hide details that are important. Let’s add a few calls topand see what we find out. Oh, and I’ll change the name of the hash from “p” to “h”. Otherwise there’s just too many “p’s” around.The above line is unnecessary. The next line assigns an array to “h”, overwriting this assignment.
Everything is exactly as it should be, even h[“a”].size returning 2. why?
Because h[“a”] is an array with two elements.
Do you see what happened?
<<appends a single element to the end of an array, and that single element is the array [“d”, “f”]. And that’s why:Because there are indeed three elements in the array: the strings “b” and “e”, and the array [“d”, “f”].
If you meant to append the elements “d” and “f” to the array, then do it with
+=: