[英]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']} 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"?例如,我有
my_hash = {"1"=> ['a'], "2"=> ['c', 'd', 'e']}
,我如何将 'b' 添加到键“ 1”?
I tried我试过了
months = Hash.new
months['1'] = ['a']
months['1'] << ['b']
But I got this result: {"111-111"=>["1111-aaaa", ["2222-bbb"]]}
但我得到了这个结果:
{"111-111"=>["1111-aaaa", ["2222-bbb"]]}
Once you've set months['1'] = ['a']
, the value of that key is an array.一旦您设置了
months['1'] = ['a']
,该键的值就是一个数组。
You want to push 'b'
into that array.您想将
'b'
推入该数组。
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)
.当您执行
<<
您必须确保该值是Array
否则它将是错误NoMethodError (undefined method << for nil:NilClass)
。 More safe to use Array.wrap
:使用
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"]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.