22
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby Hashについてまとめる

Last updated at Posted at 2015-08-10

Ruby力をつけるための基礎固めとして、Hashについて整理します。※たのしいRubyから

Hashの作り方

{ キー => 値 }

h1 = {"a" => "b", "c" => "d"}

{ キー: 値 }

h2 = {a: "b", c: "d"}

シンボルと文字列の違いは別の人が解説してくれるはず...

Hash.new

# 引数なし
h1 = Hash.new
p h1["hogehoge"] #=> nil

# 引数あ
h2 = Hash.new("")
p h2["hogehoge"] #=> ""

値を取り出す, 設定する

h = Hash.new
h["R"] = 'Ruby'
p h #=> "Ruby"
h = Hash.new
h.store("R", "Ruby")
p h.fetch("R") #=> "Ruby"

fetchで取得するときの動きの違い

# 例外が発生する
h = Hash.new
p h.fetch("N") #=> エラー(IndexError)

# 第2引数を指定すれば、キーがない場合のデフォルト値になる
h = Hash.new
p h.fetch("N", "Nothing Value") #=> "Nothing Value"

# 引数にブロックを渡すと実行結果が得られた値がデフォルト値になる
h = Hash.new
p h.fetch("N") { String.new } #=> ""

まとめて取り出す

h = { "a" => "b", "c" => "d" }
p h.keys #=> ["a", "c"]
p h.values #=> ["a", "c"]
p h.to_a #=> [["a", "b"], ["c", "d"]]

デフォルト値

ブロックを指定する

h = Hash.new do |hash, key|
  hash[key] = key.upcase
end
h["a"]
p h #=> {"a"=>"A"}

キーや値があるか確認する

h.key?(key)

h.has_key?(key)

h.include?(key)

h.member?(key)

使い方と動作は同じなので、どれか使えばOK

h = { "a" => "b", "c" => "d" }
p h.key?["a"] #=> true

h.value?(value)

h.has_value?(value)

使い方と動作は同じなので、どれか使えばOK

h = { "a" => "b", "c" => "d" }
p h.value?["b"] #=> true

ハッシュの大きさ

h.length

h.size

使い方と動作は同じなので、どれか使えばOK

h = { "a" => "b", "c" => "d" }
p h.length #=> 2
p h.size #=> 2

h.empty?(value)

h = { "a" => "b", "c" => "d" }
p h.empty? #=> false
h = Hash.new
p h.empty? #=> true

キーと値を削除する

h.delete(key)

h = { "a" => "b", "c" => "d" }
p h["a"] #=> "b"
h.delete("a")
p h["a"] #=> nil

# ブロック使った場合
h.delete("a"){ |key| "no #{key}." } "no a."

h.delete_if {key, val} ...}

h.regect! {key, val} ...}

条件を与えてそれに該当するものだけを削除

h = { "a" => "b", "c" => "d" }

# delete_if
h.delete_if{|key, value| key == "L"} #=> {"a"=>"b", "c"=>"d"}
h.delete_if{|key, value| key == "a"} #=> {"c"=>"d"}

# regect! 該当keyがなかったらnil
h.reject!{|key, value| key == "L"} #=> nil
h.reject!{|key, value| key == "a"} #=> {"c"=>"d"}

ハッシュを初期化する

h.clear

h = { "a" => "b", "c" => "d" }
h.clear #=> {}
h = { "a" => "b", "c" => "d" }
h2 = h
h.clear
p h2 #=> {}

h = { "a" => "b", "c" => "d" }
h2 = h
h = Hash.new
p h2 #=> { "a" => "b", "c" => "d" }

参考

22
18
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
22
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?