About Ruby Hashes

What is a hash?

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.

Creating a hash

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

Assign hash to variable

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"}

Element output

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

Referenced literature

Introduction to Ruby for those who want to become a professional

Recommended Posts

About Ruby Hashes
About Ruby Hashes
About Ruby Hashes (continued)
About hashes
About Ruby hashes and symbols
About Ruby symbols
About ruby ​​form
Ruby Learning # 14 Hashes
About Ruby arrays
About Ruby inheritance
About ruby block
About Ruby Symbols
About Ruby variables
About Ruby methods
About Ruby Kernel Module
About Ruby error messages
About eval in Ruby
[ruby] About here documents
About Ruby if statement
About Ruby instance methods
[Ruby] About instance generation
About the [ruby] operator
Thinking about logic Ruby
Basic methods of Ruby hashes
What you learned about hashes
Explanation about Ruby Range object
[Ruby on Rails] about has_secure_password
About regular expressions in Ruby
Ruby About various iterative processes
About =
About Ruby and object model
About Ruby classes and instances
Explanation about Ruby String object
About the behavior of ruby Hash # ==
Sorting hashes in a Ruby array
About Ruby single quotes and double quotes
About Ruby product operator (&) and sum operator (|)
[Super Introduction] About Symbols in Ruby
About object-oriented inheritance and about yield Ruby
[Ruby] Review about nesting of each
Explanation about Array object of Ruby
About method.invoke
Ruby learning 4
About Kotlin
About attr_accessor
[Ruby] Array
About Hinemos
Ruby basics
Ruby learning 5
About inheritance
Ruby basics
About params
About Docker
Refactoring Ruby
About Rails 6
About form_for
About Spring ③
[Ruby on Rails] About bundler (for beginners)
Ruby learning 3
About enum
About polymorphism