tags:

views:

49

answers:

1

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.

+5  A: 

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"]}
Wayne Conrad
Thanks Wayne for your reply. How can I insert the ["b", "e"] as an array rather than as individual elements. I want something like `{"a" =>[["b", "e"], ["d", "f"]]}`
BSingh
@BSingh Then why you didn't create it like `h = {"a" => [["b","e"]]}` and `h["a"] << ["d","f"]`?
MBO
@BSingh, I added MBO's suggestion to the top of the answer.
Wayne Conrad