Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby value of a hash key?

Tags:

hashmap

ruby

I've got a list of values that are in a Ruby hash. Is there a way to check the value of the key and if it equals "X", then do "Y"?

I can test to see if the hash has a key using hash.has_key?, but now I need to know if hash.key == "X" then...?

like image 425
cswebgrl Avatar asked Feb 20 '11 00:02

cswebgrl


People also ask

How do I get the hash value in 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.

What can be a hash key in Ruby?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.

Is a hash Ruby?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.

How do you check if a hash has 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

Hashes are indexed using the square brackets ([]). Just as arrays. But instead of indexing with the numerical index, hashes are indexed using either the string literal you used for the key, or the symbol. So if your hash is similar to

hash = { "key1" => "value1", "key2" => "value2" } 

you can access the value with

hash["key1"] 

or for

hash = { :key1 => "value1", :key2 => "value2"} 

or the new format supported in Ruby 1.9

hash = { key1: "value1", key2: "value2" } 

you can access the value with

hash[:key1] 
like image 65
Mircea Grelus Avatar answered Sep 30 '22 14:09

Mircea Grelus