开发者

Ruby: dynamically fill associative array

开发者 https://www.devze.com 2023-03-09 01:25 出处:网络
Someth开发者_如何学编程ing like that: arr=[] arr[some variable] << string How to accomplish that on Ruby?

Someth开发者_如何学编程ing like that:

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

How to accomplish that on Ruby?

Thanks ;)


In Ruby a Hash can be treated as an associative array.

# 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' }

As you can see anything can be a key, in this example I have used both a symbol, :cow and a String, 'duck'.

The Ruby Hash documentation contains all the examples you could ever need.


Hash is what you need. And you can take advantage of the default value creation when the key does not exist. That's in your case an empty array. Here is the snippet:

# 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"]  # ==> []

Check out the ruby documentation of the Hash class: http://ruby-doc.org/core/classes/Hash.html.


You can simply do this

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

or

arr[:key] = "string"

and access it like

arr["key"] 
arr[:key] 


You should use Hash instead of Array in Ruby. Arrays in Ruby are not associative.

>> h = {'a' => [1, 2]}
>> key = 'a'
>> value = 3
>> h[key] << value
>> puts h
=> {"a"=>[1, 2, 3]}
0

精彩评论

暂无评论...
验证码 换一张
取 消