Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use .reverse_merge or .merge in default methods params

You can do both

def setup(options = {})
  options.reverse_merge :size => 25, :velocity => 10
end

and

def setup(options = {})
  { :size => 25, :velocity => 10 }.merge(options)
end

to assign default values in method's params.

The question is: which one is better? Which one you would rather use? Is there any difference in performance, code readability or what ever else?

EDIT: I added bang (!) by accident... didn't mean to ask about difference between no bang method vs bang method

like image 602
Filip Bartuzi Avatar asked Sep 08 '14 12:09

Filip Bartuzi


3 Answers

I tend to use the reverse_merge approach:

options.reverse_merge(size: 25, velocity: 10)

Reason being:

  1. You don't have to write the curly brackets for the hash when the hash is used as a method argument.
  2. Reading left-to-right you know right away that this line of the code is dealing with the passed-in options hash, vs first learning about a new hash then realizing options are being merged into it.
  3. If you do want to update the original options hash it is just as easy as adding ! to the reverse_merge! method. Whereas with the other approach you now have to add a variable (re)assignment.

Ultimately, I think it's just a stylistic choice and is just up to you and what feels right to your brain.

like image 185
pdobb Avatar answered Sep 22 '22 23:09

pdobb


Merges the caller into other_hash. For example,

options = options.reverse_merge(size: 25, velocity: 10)

is equivalent to

options = { size: 25, velocity: 10 }.merge(options)

This is particularly useful for initializing an options hash with default values.


When, reverse_merge!(other_hash) public

Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second. Modifies the receiver in place.

Note: The default :size and :velocity is only set if the options passed in doesn‘t already have those keys set.

via Ruby doc.

like image 24
Gagan Gami Avatar answered Sep 24 '22 23:09

Gagan Gami


Two methods are similar, read this reverse_merge vs merge, but using Bang versions to modify the current object in place.

like image 28
Mohamed Yakout Avatar answered Sep 26 '22 23:09

Mohamed Yakout