Hash
空のハッシュの生成
code:rb
Hash({}), {}, Hash.new, Hash[]
ハッシュの生成
code:rb
capital = {:Sweden =>"Stockholm", :Norway=>"Oslo", :Finland=>"Helsinki"}
capital = {Sweden: "Stockholm", Norway: "Oslo", Finland: "Helsinki"}
to_h(二次元配列からハッシュを作成)
code:rb
1, "data 1"], [2, "data 2".to_h
# => {1=>"data 1", 2=>"data 2"}
to_a (ハッシュとキーを一つの配列として2次元配列で返す)
code:rb
h1 = { "a" => 100, 2 => "some", :c => "c" }.to_a merge(ハッシュの結合)非破壊
code:rb
h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 246, "c" => 300 }
h1.merge!(h2)
# => { "a" => 100, "b" => 246, "c" => 300}
fetch(キーにマッチした値を取得する)
code:rb
fruits = { "apple" => 100, "orange" => 80}
puts fruits.fetch("apple")
update()破壊的
code:rb
hash = {"apple" => "grate", "banana" => "ole", "orange" => "juice"}
hash.update({"grape" => "juice"})
#=> {"apple"=>"grate", "banana"=>"ole", "orange"=>"juice", "grape"=>"juice"} values_at
code:rb
hash = {price: 100, order_code: 200, order_date: "2018/09/20", tax: 0.8}
p hash.values_at(:price, :tax)
invert (ハッシュの値とキーを入れ替える(重複した場合最後の値が優先される))非破壊的
code:rb
h = { "a" => 0, "b" => 100, "c" => 200, "d" => 300, "e" => 300 }
p h.invert
#=> {0=>"a", 100=>"b", 200=>"c", 300=>"e"} include・key・member
include?(key) -> bool
key?(key) -> bool
member?(key) -> bool
hash = {price: 100, order_code: 200, order_date: "2018/09/20", tax: 0.8}
p hash.