0
0

More than 1 year has passed since last update.

Ruby Hashオブジェクト ハッシュの基礎知識

Last updated at Posted at 2022-04-20

ハッシュとは

Key(キー)とValue(バリュー)の組み合わせで関連付けを行うことができるオブジェクトです。

user1 = {id: 1, name: 'Tom'} => { :id => 1, :name => "Tom" }
user2 = {id: 1, name: 'Bob'} => { :id => 1, :name => "Bob" }

user1[:name] => "Tom"
user2[:name] => "Bob"

Keyをシンボル:で定義した場合・・・変数 = { key: value, key: value, ... }

user1 = {id: 1, name: 'Tom'} => { :id => 1, :name => "Tom" }
# シンボルで定義した Key を String で指定した場合、値を参照することはできない。
user1['name'] => nil

user3 = { 'id' => 3, 'name' => 'Jon' } => {"id"=>3, "name"=>"Jon"}
user3['name'] => "Jon"

上記のように、keyを 文字列で表す場合、keyStringで定義する必要があります。

多次元ハッシュ

ハッシュのvalueにさらにネストされたハッシュが格納されている階層構造のハッシュを指します。

user4 = {
  id: 4,
  name: 'Smith',
  test_results: {
    math: 70,
    science: 80
  }  
} => {:id=>4, :name=>"Smith", :test_results=>{:math=>70, :science=>80}}

user4[:test_results][:math] => 70
user4[:test_results][:math] = 100
user4 => {:id=>4, :name=>"Smith", :test_results=>{:math=>100, :science=>80}}

Keyの配列を取得する場合

# 該当要素のみ取得する場合
user4.key("Smith")
=> name

# 全て取得する場合
user4.keys
=> [:id, :name, :test_results]

valueの配列を取得する場合

# 該当要素のみ取得する場合
user4["name"]
=> ["Smith"]

# 全て取得する場合
user4.values
=> [4, "Smith", {:math=>100, :science=>80}]

eachメソッドhashメソッドを繰り返し処理する場合

user4 => {:id=>4, :name=>"Smith", :test_results=>{:math=>100, :science=>80}}

user4.each do |k, v|
  puts "#{k} = #{v}"
end

# 出力結果
# id = 4
# name = Smith
# test_results = {:math=>100, :science=>80}

|k, v||key, value|を省略した記述です。

keyvalueを削除する場合

deleteメソッドの第一引数に削除対象のkeyを渡すことで削除できます。

user4.delete(:test_results) => {:math=>100, :science=>80}

user4 => {:id=>4, :name=>"Smith"}

参考教材

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0