[RUBY] hash

What is a hash?

It manages multiple values ​​by giving the data and its corresponding name. The data part is called "value" and the name part is called "key".

The idea of ​​managing with such keys and values ​​is called a "key-value store".

Hashes are generated using {} (curly braces).

Write a set of key and value using hash rocket =>. Variable = {key 1 => value 1, key 2 => value 2, key 3 => value 3}

There are multiple ways to write hashes, and some are written using symbols.

The symbol looks like a string, but the actual content is a number.

To declare a symbol, add a colon: at the beginning of the string. If the strings are the same, the contents will be the same regardless of whether the strings are quoted or not.

:"Hello"

:Hello

#Both have the same value

Computers process numbers faster than they handle strings, so they can be faster and can also serve as strings, so hash keys are more symbols than strings. Is often used.

Let's actually generate a hash.

son = { "name" => "Nick", "age" => 12 }
father = { name: "George", age: 38 }

If you want to add an element to the hash

Hash [key to add] = value.

son = { "name" => "Nick", "age" => 12 }
father = { name: "George", age: 38 }

father[:hobby] = "fishing"    #Added key hobby value fishing

Get the hash value

Hash [key of the value you want to get].

son = { "name" => "Nick", "age" => 12 }
father = { name: "George", age: 38, hobby: "fishing" }

puts father[:age]  #38 is output

Change hash value

Hash [key of the value you want to change] = value.

son = { "name" => "Nick", "age" => 12 }
father = { name: "George", age: 38, hobby: "fishing" }

father[:age] = 40

puts father[:age]  #Output as 40

that's all.

Recommended Posts

hash
Hash
Hash basics
Ruby Hash notes
[Ruby] Hash retrieval
[About double hash]
[ruby] Double hash
Ruby double hash
[Rails] About active hash
[Rails] Introducing Active Hash
Utilization of Active Hash
Explaining Ruby's Hash object
hash and each statement
Pitfalls of Active Hash