A Hash is like a cabinet full of tagged folders. When you open the cabinet, you can choose the folder at a glance. A Hash stores data in key/value pairs. The new hash is the cabinet (just think about it as the name of the hash), the keys are the tagged folders, and the values are the sheets of paper inside the folder (think of the papers as Strings, Numbers, Arrays, etc).
Hash keys, unlike like Arrays, can be: (1) strings, (2) numbers, (3) symbols and (4) arrays (though i don't see any use for this).
Unlike arrays, theres no need to know the order of the item. Therefore, a Hash is very useful for storing data (models) without any particular order.
Hash values can be any ruby object. E.g: objects, methods, strings, numbers, floats, etc.
There a are two ways to create a hash.
You create an instance of the the Hash
object using the .new
method.
new_hash = Hash.new # Hash needs to be Capitalized, as you're creating an instance of the Hash object
new_hash["name"] = "Jose" # You assign a value to the hash key using the =
new_hash["last_name"] = "Rosado"
You create an instance of the the Hash
object using curly braces {}
.
short_hash = {
"name" => "Jose", # Always add a comma after the value
:last => "Rosado", # You may use symbols as key.
last_name: "Rosado", # This is another way to use symbols as key.
0 => "You can use numbers", # just like arrays.
[1] => "This is number 1" # Heck!, you could even use an array... but don't do this
# No need to add comma to after the last value
}
You retrieve data using brackets []
, just like an Array, but using the key instead of a number.
puts new_hash["name"] # => "Jose"
puts new_hash["last_name"] # => "Rosado"
puts "#{new_hash['name']} #{new_hash['last_name']}" # => José Rosado