Skip to content

Instantly share code, notes, and snippets.

@benzittlau
Created February 10, 2017 20:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benzittlau/e828bc97a9c066517416548e5813bd9a to your computer and use it in GitHub Desktop.
Save benzittlau/e828bc97a9c066517416548e5813bd9a to your computer and use it in GitHub Desktop.
Merging defaults with options hash in a ruby function
# Related area of style guide: https://github.com/GetJobber/ruby-style-guide#hash-fetch-defaults
# Pros: Is succinct and intuitive
# Cons: Doesn't work for false values
def default_one(options)
options[:foo] ||= 'foo'
options[:bar] ||= 'bar'
end
# Pros: Handles false without issue, is succient
# Cons: Less intuitive if you're not familiar with the behaviour of merge. This line is somewhat cryptic: options = defaults.merge(options)
# Involves shadowing "options" with a merged version of options.
def default_two(options)
defaults = {:foo => 'foo', :bar => 'boo'}
options = defaults.merge(options)
end
# Source: http://stackoverflow.com/questions/977535/whats-a-nice-clean-way-to-use-an-options-hash-with-defaults-values-as-a-paramet
# Pros: Handles false without issue, is even more succient than option 2, maybe more intuitive than option 2
# Cons: You're even less likely to intuitively know what a `reverse_merge` is than `merge`, but you can probably guess from context
def default_three(options)
options.reverse_merge!{
:foo => 'foo',
:bar => 'bar'
}
end
@benzittlau
Copy link
Author

benzittlau commented Feb 22, 2017

def default_four(options)
  options[:foo] = 'foo' unless options.has_key?(:foo)
  options[:bar] = 'bar' unless options.has_key?(:bar)
end

def default_five(options)
  options[:foo] = options.fetch(:foo, 'foo')
  options[:bar] = options.fetch(:bar, 'bar')
end

@benzittlau
Copy link
Author

benzittlau commented Feb 22, 2017

def default_six(options)
  defaults = {:foo => 'foo', :bar => 'boo'}
  
  options.reverse_merge!(defaults)
end

@benzittlau
Copy link
Author

Decision, we'll run with default_six as our convention for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment