Is there an idiomatic way to specify default values โ€‹โ€‹for optional parameters in Ruby?

Is there a more concise and idiomatic way to write the following code, which is used to specify default values โ€‹โ€‹for optional parameters (in the params / options hash) to the method?

def initialize(params={}) if params.has_key? :verbose @verbose = params[:verbose] else @verbose = true # this is the default value end end 

I would like to simplify it like this:

 def initialize(params={}) @verbose = params[:verbose] or true end 

which almost works, except you really need to use has_key? :verbose has_key? :verbose as a condition, not just evaluate params[:verbose] to cover cases where you want to specify a value of "false" (that is, if you want to pass :verbose => false as an argument in this example).

I understand that in this simple example, I could easily do:

 def initialize(verbose=false) @verbose = verbose end 

but in my real code, I actually have a bunch of optional parameters (in addition to a few mandatory ones), and I would like to put the optional params in the hashes so that I can just specify (by name) the few that I want, instead of to list them all in order (and maybe list them that I really don't want).

+4
source share
4 answers

A common pattern is to use

 def foo(options = {}) options = { :default => :value }.merge(options) end 

As a result, you will get an options hash containing the passed values, with the default hash settings that were provided.

+14
source

Ruby 2.0.0 has a new keyword arguments function

You used to write code like this:

 def foo(options = {}) options = {bar: 'bar'}.merge(options) puts "#{options[:bar]} #{options[:buz]}" end foo(buz: 'buz') # => 'bar buz' 

Now this is much cleaner:

 def foo(bar: 'bar', **options) puts "#{bar}, #{options}" end foo(buz: 'buz') # => 'bar buz' 
+2
source

I think you are looking for it.

 params = { :verbose => true }.merge(params) 
0
source

Another way to write this, more succinctly, would be

 def foo(options = {}) options.reverse_merge! value1: true, value2: 100 end 

Sets the parameters [: value1] to true (the default value), if the parameters are not passed already contains the key: value1. Same for: value2

0
source

All Articles