Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a Ruby hash with a variable as the key

Tags:

ruby

If I had the following ruby hash:

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

How would I access parts of the above hash? An example below as to what I am trying to achieve.

current_environment = 'testing'
"rsync -ar root@#{environments[#{testing}]}:/htdocs/"
like image 618
Craig Ward Avatar asked Apr 29 '13 22:04

Craig Ward


People also ask

How do you access a hash Ruby?

In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.

How do you call a hash value in Ruby?

Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated. Hashes can be created with two syntaxes. The older syntax comes with a => sign to separate the key and the value.

How do you check if a hash contains a key Ruby?

Overview. We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.


1 Answers

You would use brackets:

environments = {
   'testing' =>  '11.22.33.44',
   'production' => '55.66.77.88'
}
myString = 'testing'
environments[myString] # => '11.22.33.44'
like image 84
tckmn Avatar answered Sep 30 '22 19:09

tckmn