简体   繁体   中英

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.

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} .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM