Explaining Ruby's Hash object

What is Hash?

A Hash object is an object that can represent data with a combination of key and value.

How to write Hash

Hash is created with curly braces and a colon.

irb(main):082:0> user = { name: 'Masuyama' }
=> {:name=>"Masuyama"}

Hash value retrieval type

In the case of the colon-based notation as before, the key is a symbol object, so You can retrieve the corresponding value by specifying symbol in the hash object.

irb(main):083:0> user[:name]
=> "Masuyama"

Hash rewrite

You can also rewrite the value by specifying a specific key and assigning the value.

irb(main):095:0> user = { name: 'Masuyama' }
=> {:name=>"Masuyama"}
irb(main):096:0> user[:name] = 'Yamada'
=> "Yamada"
irb(main):097:0> user[:name]
=> "Yamada"

Get a list of keys

You can get the keys as an array using the keys method.

irb(main):110:0> users = { id: 1, name: 'Masuyama', age
: 29 }
=> {:id=>1, :name=>"Masuyama", :age=>29}
irb(main):111:0> users.keys
=> [:id, :name, :age]

Get a list of values

Like keys, you can use the values method to get the values as an array.

irb(main):112:0> users = { id: 1, name: 'Masuyama', age
: 29 }
=> {:id=>1, :name=>"Masuyama", :age=>29}
irb(main):113:0> users.values
=> [1, "Masuyama", 29]

each method in hash

In hash, you can process each element with each method. If you use the each method for hash, you will be passing both key and value to the block.

irb(main):118:1* users.each do |k, v|
irb(main):119:1*   puts "#{k} = #{v}"
irb(main):120:0> end
id = 1
name = Masuyama
age = 29
=> {:id=>1, :name=>"Masuyama", :age=>29}

Delete hash value

Use the delete method to delete some key and value. At this time, specify the key to be deleted in the first argument.

irb(main):124:0> users
=> {:id=>1, :name=>"Masuyama", :age=>29}
irb(main):125:0> users.delete(:age)
=> 29
irb(main):126:0> users
=> {:id=>1, :name=>"Masuyama"}

Recommended Posts

Explaining Ruby's Hash object
Explaining Ruby's Symbol object
Explaining Ruby's Enumerator object
hash
Hash