コンテンツにスキップ

ハッシュの操作

ハッシュの初期化

以下の方法でハッシュのインスタンスを生成できる。

  • {}
  • Hash[]
  • Hash({})
  • Hash.new
hash = {}                           # => {}
hash = { "one" => 1, "two" => 2 }   # => { "one" => 1, "two" => 2 }

Hash[]                              # => {}
Hash["a", "b"]                      # => {"a"=>"b"}
Hash["a", "b", "c", "d"]            # => {"a"=>"b", "c"=>"d"}

Hash.new                            # => {}
h = Hash.new("foo")                 # => {}
h[1]                                # => "foo" / デフォルト値が設定される

Hash#to_a

  • ハッシュを配列に変換する。
hash = {"apple" => "grate", "banana" => "ole", "orange" => "juice"}
hash.to_a   # => [["apple", "grate"], ["banana", "ole"], ["orange", "juice"]]

Hash#clear

  • ハッシュの中身を空にする。
hash = {"apple" => "grate", "banana" => "ole", "orange" => "juice"}
hash.clear  # => {}

Hash#has_key?

  • ハッシュのキーが存在するかどうかを返す。
  • 以下の別名メソッドがある。
    • Hash#key?
    • Hash#include?
    • Hash#member?
{1 => "one"}.key?(1)  # => true
{1 => "one"}.key?(2)  # => false

Hash#fetch

  • キーにマッチした値を取得する。
  • h[:key] でも可能だが、キーが存在しない場合は nil を返す。
h = {one: nil}
p h[:one],h[:two]                        # => nil,nil これではキーが存在するのか判別できない。
p h.fetch(:one)                          # => nil
p h.fetch(:two)                          # エラー key not found (KeyError)
p h.fetch(:two,"error")                  # => "error"

h.default = "default"
p h.fetch(:two)                          # エラー key not found (KeyError)

Hash#invert

  • ハッシュのキーと値を入れ替える。
  • 異なるキーに対して等しい値が登録されている場合、最後に定義されている値が使用される。

非破壊的メソッドであり、 Hash#invert! は存在しない。

h = { "a" => 0, "b" => 100, "c" => 200, "d" => 300, "e" => 300 }
p h.invert   # => {0=>"a", 100=>"b", 200=>"c", 300=>"e"}

Hash#merge

  • ハッシュをマージし、新しいハッシュを返す。
h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 246, "c" => 300 }
h3 = { "b" => 357, "d" => 400 }
h1.merge          # => {"a"=>100, "b"=>200}
h1.merge(h2)      # => {"a"=>100, "b"=>246, "c"=>300}
h1.merge(h2, h3)  # => {"a"=>100, "b"=>357, "c"=>300, "d"=>400}

p h1              # => {"a"=>100, "b"=>200}

Hash#merge!

  • ハッシュをマージする。
  • Hash#update は別名メソッド
h1 = { "a" => 100, "b" => 200 }
h1.merge!           # => {"a"=>100, "b"=>200}
h1                  # => {"a"=>100, "b"=>200}

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 246, "c" => 300 }
h1.merge!(h2)       # => {"a"=>100, "b"=>246, "c"=>300}
h1                  # => {"a"=>100, "b"=>246, "c"=>300}

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 246, "c" => 300 }
h3 = { "b" => 357, "d" => 400 }
h1.merge!(h2, h3)   # => {"a"=>100, "b"=>357, "c"=>300, "d"=>400}
h1                  # => {"a"=>100, "b"=>357, "c"=>300, "d"=>400}
foo = {1 => 'a', 2 => 'b', 3 => 'c'}
bar = {2 => 'B', 3 => 'C', 4 => 'D'}

p foo.update(bar)   # => {1=>"a", 2=>"B", 3=>"C", 4=>"D"}
p foo               # => {1=>"a", 2=>"B", 3=>"C", 4=>"D"}