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
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).
source share