简体   繁体   中英

Add elements to an array in a hash

I have a file with a table that show a relationship between some users:

user1.  user2
a.       1
b.       1
c.       2
d.       2
e.       2

...

For this I want to create this kind of hash:

my_hash = {"1"=> ['a','b'], "2"=> ['c', 'd', 'e']}

The problem I'm having right now is I can't find a way to add to the array:

Fo example, I have my_hash = {"1"=> ['a'], "2"=> ['c', 'd', 'e']} , how do I add 'b' to the key "1"?

I tried

months = Hash.new

months['1'] = ['a']

months['1'] << ['b']

But I got this result: {"111-111"=>["1111-aaaa", ["2222-bbb"]]}

Once you've set months['1'] = ['a'] , the value of that key is an array.

You want to push 'b' into that array.

irb> months = Hash.new
=> {}
irb> months['1'] = ['a']
=> ["a"]
irb> months['1'] << 'b'
=> ["a", "b"]

When you do << you have to be sure that value is Array or it will be error NoMethodError (undefined method << for nil:NilClass) . More safe to use Array.wrap :

h = {}
h['1'] = Array.wrap(h['1']).push('A')
h['1'] = Array.wrap(h['1']).push('B')
h['2'] = Array.wrap(h['2']).push('C')  

# h is  {"1"=>["A", "B"], "2"=>["C"]}

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