The default parameter is false.

This is the usual way to set the default value in Ruby:

class QuietByDefault
  def initialize(opts = {})
    @verbose = opts[:verbose]
  end
end

This is a simple trap that falls into:

class VerboseNoMatterWhat
  def initialize(opts = {})
    @verbose = opts[:verbose] || true
  end
end

This is the right way to do this:

class VerboseByDefault
  def initialize(opts = {})
    @verbose = opts.include?(:verbose) ? opts[:verbose] : true
  end
end

What is the best / cleanest way to code VerboseByDefault? (Of course, I could rule that out.)

What pattern is widely used, if any, in Ruby code at all? Does ActiveSupport have a template for this? (Minimally better - I don't need a complete command line parser.)

PS Repeat: I don't like the asymmetry between the code that processes the default code trueversus the code that processes the default parameter false. An image that makes a change between the two โ€” without error โ€” would be good to see.

+5
3

- Hash # fetch

class VerboseByDefault
  def initialize(opts = {})
    @verbose = opts.fetch(:verbose, true)
  end
end

, fetch , , . .: http://ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch

+7

, . ..

def initialize(opts = {})
  @options = { :verbose => false, :foo => 42 } 
  @options.merge!(opts)
  # ...
end

, , .

+1
require 'active_support/core_ext/hash/reverse_merge'
class VerboseByDefault
  DEFAULTS = { verbose: true }
  def initialize(opts = {})
    opts.reverse_merge!(DEFAULTS)
    @verbose = opts[:verbose]
  end
end

Not only is this a little cleaner for just one option, but it gets better if you have more options. In addition, it uses the same pattern for trueand false.

0
source

All Articles