ruby merge two hashes code example

Example 1: ruby merge array of hashes into one hash

a.inject(:merge)
#=> {:a=>:b, :c=>:d}

Example 2: ruby merge array of hashes into one hash

a.reduce Hash.new, :merge

Example 3: ruby hash merge

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
h1.merge(h2){|key, oldval, newval| newval - oldval}
               #=> {"a"=>100, "b"=>54,  "c"=>300}
h1             #=> {"a"=>100, "b"=>200}

Example 4: how to add two variables into a hash ruby

your_hash = {}
hash_key = gets.chomp
hash_value = gets.chomp
your_hash[hash_key] = hash_value

Tags:

Ruby Example