Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby hash direct access vs merge

Tags:

merge

ruby

hash

Is there any difference between:

@attr[:field] = new_value

and

@attr.merge(:field => new_value)
like image 912
eMgz Avatar asked May 16 '11 14:05

eMgz


People also ask

How do you merge hashes in Ruby?

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 are hashes used for in Ruby?

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.

How do you define a hash in Ruby?

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.


3 Answers

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

like image 185
Simon Woker Avatar answered Oct 25 '22 19:10

Simon Woker


They do the same thing, however:

@attr[:field] = new_value

is more efficient, since no hash traversing is necessary.

like image 37
Milan Dobrota Avatar answered Oct 25 '22 21:10

Milan Dobrota


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
like image 44
Snehal Ahire Avatar answered Oct 25 '22 19:10

Snehal Ahire