0

Something like that:

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

How to accomplish that on Ruby?

Thanks ;)

1
  • 1
    What are you trying to accomplish, i.e., what should arr be after this? I can't tell if you're just trying to set a hash value (e.g., h={}; h[key]=value) or do something else. Commented May 30, 2011 at 15:20

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mate i have already found that out :D. Btw what differens in [:cow] and ['cow'] ?
They're just different classes used as keys. You can have both in the same hash { :cow => 'moo', 'cow' => 'moo' }
4

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.

Comments

0

You can simply do this

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

or

arr[:key] = "string"

and access it like

arr["key"] 
arr[:key] 

Comments

0

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]}

3 Comments

what happened to the old h[key] = value?
More elegant solution? Doesn't Ruby have the most beautiful and elegant syntax? :D
Why do the examples call send?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.