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/"
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.
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.
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.
You would use brackets:
environments = {
'testing' => '11.22.33.44',
'production' => '55.66.77.88'
}
myString = 'testing'
environments[myString] # => '11.22.33.44'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With