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
I tend to use the reverse_merge
approach:
options.reverse_merge(size: 25, velocity: 10)
Reason being:
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.
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.
Two methods are similar, read this reverse_merge vs merge, but using Bang versions to modify the current object in place.
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