Ruby: Creating a Hash Key and Value from a Variable in Ruby

Ruby: Creating a hash key and value from a variable in Ruby

If you want to populate a new hash with certain values, you can pass them to Hash::[]:

Hash["a", 100, "b", 200]             #=> {"a"=>100, "b"=>200}
Hash[ [ ["a", 100], ["b", 200] ] ] #=> {"a"=>100, "b"=>200}
Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200}

So in your case:

Hash[id, 'foo']
Hash[[[id, 'foo']]]
Hash[id => 'foo']

The last syntax id => 'foo' can also be used with {}:

{ id => 'foo' }

Otherwise, if the hash already exists, use Hash#=[]:

h = {}
h[id] = 'foo'

How to set a hash key using a variable in Ruby 1.9?

Let me introduce you two ways to do what you exactly want. If you don't want to continue using 1.8 syntax and hashrockets anymore, ruby-doc.org recommends doing it in this way in Ruby 1.9.3:

my_hash = Hash.new

my_key = "key000"
my_hash[my_key] = "my_value"

Livedemo: http://ideone.com/yqIx2M

Second one (more similar to what you are trying to achieve) is:

my_key = "key0"
my_hash = Hash[my_key, "value00"]

puts my_hash

Livedemo: http://ideone.com/HHLyAi

How to access a symbol hash key using a variable in Ruby

You want to convert your string to a symbol first:

another_family[somevar.to_sym]

If you want to not have to worry about if your hash is symbol or string, simply convert it to symbolized keys

see: How do I convert a Ruby hash so that all of its keys are symbols?

How do I set a variable as a key when I call my hash value?

The easiest is just to update

puts "point #{card_value[:card]}"

To

puts "point #{card_value[random_card.to_sym]}"

The reason is card_value[:card] is trying to get from the card_value hash they card key, which doesn't exist.

Your random_card function returns a "random" string value from the cards array defined in its body, being a string, you'll get the same error, as the keys in the card_value are symbols, so you need to convert that result to a symbol.



Answering to the dx7 nice addition.

You can just declare a CARD_VALUES hash, containing card names and points, which you can then pick up with Array#sample, so you avoid adding a useless instance variable for the card, and having to pass it as a method argument when calling random_card:

CARD_VALUES = { two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10,
jack: 10, queen: 10, king: 10, ace: 11 }

def random_card
CARD_VALUES.to_a.sample
end

def move
loop do
puts '"hit" or "stick"'
input = gets.chomp
if input == 'hit'
card, point = random_card
puts "card: #{card}"
puts "point: #{point}"
end
break if input == 'stick'
end
end

move

Accessing a Ruby hash with a variable as the key

It looks like you want to exec that last line, as it's obviously a shell command rather than Ruby code. You don't need to interpolate twice; once will do:

exec("rsync -ar root@#{environments['testing']}:/htdocs/")

Or, using the variable:

exec("rsync -ar root@#{environments[current_environment]}:/htdocs/")

Note that the more Ruby way is to use Symbols rather than Strings as the keys:

environments = {
:testing => '11.22.33.44',
:production => '55.66.77.88'
}

current_environment = :testing
exec("rsync -ar root@#{environments[current_environment]}:/htdocs/")

Ruby instance variable and hash key - how it works

Ruby is one of many languages that distinguish "immediate values" and "reference values".

If I say x = 5; y = x; y = 6, then x is an immediate value, and still contains 5, not 6.

But if I say x = { value: 5 }, then x is a reference to a hash object. When I say y = x then y refers to the same hash object as x does. So y[:value] = 6 will make x[:value] == 6.

To prevent this behavior, look up "ruby deep copy", and use y = x.dup.

How to change the value of a variable which is a value in a hash (using the hash)?

I wonder why you would want to do such a thing, but you could store the names of the variables instead of the variables themselves:

bar = "ruby"
foo = {key: 'bar'}

Setting a variable:

eval("#{foo[:key]} = 'rails'")
p foo # {:key=>"bar"}
p bar # "rails"

Getting a variable:

eval(foo[:key])

Storing a function in the value for a key within a hash

You can use the send keyword

send h[step]

since you writing the method name directly in value part of the hash, the call is being made, but If you store the method names as a string and then if you call by send method as shown below, it would work.

def hi
puts 'hi'
end

def hello
puts 'hello'
end

h = {
1 => 'hi',
2 => 'hello',
}

send h[1]


Related Topics



Leave a reply



Submit