A hash is an object that manages data with a combination of keys and values.
If you want to create a hash, use a syntax like this:
{Key 1 => Value 1, Key 2 => Value 2, Key 3 => Value 3}
Example of actually creating a hash
{'food' => 'rice', 'fruit' => 'lemon'}
If you want to add a new key and value after creating the hash, use the following syntax.
Hash [key] = value
(Example) The following is the code to add a new drink type.
menu = { 'food' => 'rice', 'fruit' => 'lemon', }
#Add a drink menu
menu['drink'] = 'water'
puts menu #=> {"food" => "rice", "fruit" => "lemon", "drink" => "water"}
If the key already exists, the value will be overwritten.
menu = { 'food' => 'rice', 'fruit' => 'lemon', }
#Overwrite the value
menu['food'] = 'pizza'
puts menu #=> {"food" => "pizza", "fruit" => "lemon"}
You can use the each method to retrieve a set of keys and values in sequence.
menu = { 'food' => 'rice', 'fruit' => 'lemon', }
menu.each do |key, value|
puts "#{key} : #{value}"
end
# => food : rice
# fruit : lemon
When using each method for hash, specify "key" and "value" for variables. |variable|のvariableはブロック引数といい、eachメソッドから渡されたハッシュの要素が入る。 The "key" of the hash is assigned to the variable key, and the "value" is assigned to the variable value in order. Then, after the process described in the block is repeatedly executed for the number of hash elements, the process of exiting the block ends.
Introduction to Ruby for those who want to become professionals
Recommended Posts