Ruby/Hash/merge
Материал из Wiki.crossplatform.ru
Версия от 17:57, 13 сентября 2010; ViGOur (Обсуждение | вклад)
Содержание |
merge method merges two hashes together, producing a copy of the hashes that removes duplicate keys by overwriting the key-value pairs from the merged array.
myHash2 = { 1 => "Two", 2 => "New Value", 3 => "New Three" } myHash = { 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four", 5 => "Five" } myHash.merge myHash2 p myHash
Merge two hashes
delaware = { 1 => "Two", 2 => "New Value", 3 => "New Three" } myHash = { 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four", 5 => "Five" } myHash.merge delaware # => {5=>"Five", 1=>"Two", 2=>"New Value", 3=>"New Three", 4=>"Four"}
Merge two hashes with block logics
delaware = { 1 => "Two", 2 => "New Value", 3 => "New Three" } myHash = { 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four", 5 => "Five" } myHash.merge( delaware ){|key,old,new| new = old + "_new" } # => {5=>"Five", 1=>"One_new", 2=>"Two_new", 3=>"Three_new", 4=>"Four"}
using merge with a block
myHash2 = { 1 => "Two", 2 => "New Value", 3 => "New Three" } myHash = { 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four",5 => "Five" } myHash.merge( myHash2 ){|key,old,new| new = old + "_new" }