Edited to add: Your comments indicate that you want for element 'a' to be an array of arrays. Here it is:
h = Hash.new
h = {"a" => [["b","e"]]}
p h # => {"a"=>[["b", "e"]]}
h["a"] << ["d", "f"]
p h # => {"a"=>[["b", "e"], ["d", "f"]]}
When diagnosing a problem, prefer p
to puts
. puts
can hide details that are important. Let's add a few calls to p
and 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.
h = Hash.new
The above line is unnecessary. The next line assigns an array to "h", overwriting this assignment.
h = {"a" => ["b","e"]}
p h # => {"a"=>["b", "e"]}
p h["a"].size # 2
Everything is exactly as it should be, even h["a"].size returning 2. why?
p h["a"] # => ["b", "e"]
Because h["a"] is an array with two elements.
h["a"] << ["d", "f"]
p h # => {"a"=>["b", "e", ["d", "f"]]}
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:
p h["a"].size # => 3
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 +=
:
h = {"a" => ["b","e"]}
h["a"] += ["d", "f"]
p h # => {"a"=>["b", "e", "d", "f"]}