如何解决Ruby:动态填充关联数组
| 像这样:arr=[]
arr[some variable] << string
如何在Ruby上实现?
谢谢 ;)
解决方法
在Ruby中,“ 1”可以视为关联数组。
# Initialize the hash.
noises = {}
# => {}
# Add items to the hash.
noises[:cow] = \'moo\'
# => { :cow => \'moo\' }
# Dynamically add items.
animal = \'duck\'
noise = \'quack\'
noises[animal] = noise
# => { :cow => \'moo\',\'duck\' => \'quack\' }
如您所见,任何东西都可以是键,在本示例中,我同时使用了符号:cow
和字符串\'duck\'
。
Ruby Hash文档包含您可能需要的所有示例。
, 哈希是您所需要的。当键不存在时,您可以利用默认值创建功能。在您的情况下,那是一个空数组。这是代码段:
# this creates you a hash with a default value of an empty array
your_hash = Hash.new { |hash,key| hash[key] = Array.new }
your_hash[\"x\"] << \"foo\"
your_hash[\"x\"] << \"za\"
your_hash[\"y\"] << \"bar\"
your_hash[\"x\"] # ==> [\"foo\",\"za\"]
your_hash[\"y\"] # ==> [\"bar\"]
your_hash[\"z\"] # ==> []
查看Hash类的ruby文档:http://ruby-doc.org/core/classes/Hash.html。
, 你可以简单地做到这一点
arr={}
arr[\"key\"] = \"string\"
要么
arr[:key] = \"string\"
并像访问
arr[\"key\"]
arr[:key]
, 您应该在Ruby中使用Hash而不是Array。 Ruby中的数组不是关联的。
>> h = {\'a\' => [1,2]}
>> key = \'a\'
>> value = 3
>> h[key] << value
>> puts h
=> {\"a\"=>[1,2,3]}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。