Ruby:动态填充关联数组

Ruby:动态填充关联数组,ruby,Ruby,诸如此类: arr=[] arr[some variable] << string arr=[] arr[some variable]在Ruby中应该使用哈希而不是数组。Ruby中的数组是不关联的 >> h = {'a' => [1, 2]} >> key = 'a' >> value = 3 >> h[key] << value >> puts h => {"a"=>[1, 2, 3]}

诸如此类:

arr=[]
arr[some variable] << string
arr=[]

arr[some variable]在Ruby中应该使用哈希而不是数组。Ruby中的数组是不关联的

>> h = {'a' => [1, 2]}
>> key = 'a'
>> value = 3
>> h[key] << value
>> puts h
=> {"a"=>[1, 2, 3]}
>h={'a'=>[1,2]}
>>键='a'
>>值=3
>>h[键]>放置h
=>{“a”=>[1,2,3]}

在Ruby中,哈希可以被视为关联数组

# 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包含了您可能需要的所有示例。

您可以简单地做到这一点

arr={}
arr["key"] = "string"

然后像这样访问它

arr["key"] 
arr[:key] 

哈希是你需要的。当密钥不存在时,您可以利用默认值创建。在您的例子中,这是一个空数组。以下是片段:

# 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=hash.new{| hash,key | hash[key]=Array.new}
您的_散列[“x”][]

查看Hash类的ruby文档:。

旧的h[key]=value发生了什么?更优雅的解决方案?Ruby难道没有最漂亮、最优雅的语法吗为什么示例调用
send
?谢谢,伙计,我已经找到了答案:D.顺便说一句,[:cow]和['cow']有什么不同?它们只是用作键的不同类。您可以在同一个散列中同时拥有这两个属性
{:cow=>'moo',cow'=>'moo'}您试图实现什么,即,在此之后应该是什么?我无法判断您是否只是试图设置哈希值(例如,h={};h[key]=value)或执行其他操作。
# 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"]  # ==> []