標準クラス・モジュール > Hash > update
hash.update(other_hash) hash.update(other_hash) {|key, oldval, newval| block }
update
メソッドは、merge!
の別名です。レシーバhashの内容に引数other_hashの内容を加えます。詳しい説明はmerge, merge!
をご覧ください。
image = { :src => "monkey.jpg", :alt => "monkey" } image.update(:width => 320, :height => 240) puts image[:src], image[:width]
monkey.jpg 320
ブロックを渡すと、重複するキーがあるときの値を決められます。
image1 = { :src => "monkey.jpg", :alt => "monkey", :width => 320, :height => 240 } image2 = { :src => "pelican.jpg", :alt => "pelican", :width => 640, :height => 480 } image1.update(image2) do |key, oldval, newval| [:src, :alt].include?(key) ? oldval : newval end puts image1[:src], image1[:width]
monkey.jpg 640
merge, merge!
: 2つのハッシュを統合。