Is there any difference between:
@attr[:field] = new_value
and
@attr.merge(:field => new_value)
                Hash#merge!() is a Hash class method which can add the content the given hash array to the other. Entries with duplicate keys are overwritten with the values from each other_hash successively if no block is given.
What is a Ruby hash? A hash is a data structure used to store data in the form of UNIQUE key-value pairs. Unlike arrays, there are no numerical indexes, you access the hash values with keys.
In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.
If you're using merge! instead of merge, there is no difference.
The only difference is that you can use multiple fields (meaning: another hash) in the merge parameters.  
Example:
   h1 = { "a" => 100, "b" => 200 }
   h2 = { "b" => 254, "c" => 300 }
   h3 = h1.merge(h2)    
   puts h1         # => {"a" => 100, "b" => 200}
   puts h3         # => {"a"=>100, "b"=>254, "c"=>300}
   h1.merge!(h2)   
   puts h1         # => {"a"=>100, "b"=>254, "c"=>300}
When assigning single values, I would prefer h[:field] = new_val over merge for readability reasons and I guess it is faster than merging.
You can also take a look at the Hash-rdoc: http://ruby-doc.org/core/classes/Hash.html#M000759
They do the same thing, however:
@attr[:field] = new_value
is more efficient, since no hash traversing is necessary.
Merge returns a new hash at a different location merging other_hashes into self but Merge! operated like "update" returning self hash, copying at self-location.
    h1 = { "a": 1 }
    h2 = { "b": 2 }
    def merge_hash (a,b)
      puts h1                 # {:a=> 1}
      puts h1.object_id       # 340720
  
      h1 = h1.merge(h2)
      puts h1                 # {:a=>1, :b=>2}
      puts h1.object_id       # 340760
    end
    merge_hash(h1, h2)
    puts h1                     # {:a=> 1}
    h1.object_id                # 340720
    def merge_hash (a,b)
      puts h1                 # {:a=> 1}
      puts h1.object_id       # 340720
  
      h1 = h1.merge!(h2)
      puts h1                 # {:a=>1, :b=>2}
      puts h1.object_id       # 340720
    end
    merge_hash(h1, h2)
    puts h1                     # {:a=>1, :b=>2}
    h1.object_id                # 340720
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With