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 a method?
def initialize(params={})
if params.has_key? :verbose
@verbose = params[:verbose]
else
@verbose = true # this is the default value
end
end
I would love to simplify it to something like this:
def initialize(params={})
@verbose = params[:verbose] or true
end
which almost works, except that you really need to use has_key? :verbose
as the condition, instead of just evaluating params[:verbose]
, in order to cover cases when you want to specify a value of 'false' (i.e. if you want to pass :verbose => false
as the argument in this example).
I realize 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 required ones) and I'd like to put the optional ones in the params hash so that I can easily only specify (by name) the few that I want, rather than having to list them all in order (and potentially having to list ones I don't actually want).