AnthonyW
AnthonyW

Reputation: 1998

Ruby hash of arrays, retrieving values

I have been all over the interwebs and cannot seem to find out how to access an array within a hash. Plenty of ways to iterate through as well as flatten but no plain access.

hash = Hash.new()
data1 = "foo"
data2 = "bar"
hash["foobar"] = {data1, data2}

This all works, now how can I access data1 and data2 individually within the hash?

I was thinking puts hash["foobar"][0] should output foo but it returns nil.

Note: Every array in the hash will have Exactly 2 elements.

I know the answer is a simple 1 liner, I just cannot seem to find it.

Upvotes: 0

Views: 700

Answers (1)

As I commented on the question, array literals are square brackets [ ], not curly braces { }. Change your last line to:

hash["foobar"] = [data1, data2]

(You were getting nil presumably because the hash literal had no 0 key. Testing here reveals that , can apparently function as => (*shudder*), so your iteral was equivalent to {data1 => data2}.)

Upvotes: 2

Related Questions