A hash is an object that manages data with a combination of keys and values. Arrays manage multiple values side by side, while hashes manage each value with a name called a key.
When creating a hash, use the following syntax (hash literal):
index.rb
#A hash that stores two key / value combinations
{Key 1=>Value 1,Key 2=>Value 2}
(Example) Connect the key and value with =>. Separate elements with commas (,).
index.rb
{"fruit" => "apple", "color" => "red}
A hash is an object of the Hash class. If you create an empty hash {} on the console and look at its class name, you'll see that it's Hash.
{}.class
result
=> Hash
You can assign a hash to a variable. (Example)
index.rb
fruit = {"apple" => "red", "lemon" => "yellow", "melon" => "green"}
puts fruit
result
{"apple" => "red", "lemon" => "yellow", "melon" => "green"}
The value of each element of the hash can be output using the corresponding key.
(Example)
index.rb
fruit = {"apple" => "red", "lemon" => "yellow", "melon" => "green"}
puts fruit["apple"]
result
red
Introduction to Ruby for those who want to become a professional
Recommended Posts