Skip to content

Instantly share code, notes, and snippets.

@garethrees
Last active October 12, 2015 14:08
Show Gist options
  • Save garethrees/4038774 to your computer and use it in GitHub Desktop.
Save garethrees/4038774 to your computer and use it in GitHub Desktop.
Hash arguments, default values and asserting valid keys
def donate_to_charity(args = {})
# Set valid options that can be supplied. All others will be cut.
valid_args = [:user_id, :charity_id, :amount]
# Set default options if none are supplied
defaults = { :user_id => nil,
:charity_id => 1,
:amount => 25 }
# Raise ArgumentError if invalid keys are passed
args.assert_valid_keys(*valid_args)
# Overwrite defaults with any arguments passed in
opts = defaults.merge(args)
# Set local variables to use in method (optional)
user_id = opts[:user_id]
charity_id = opts[:charity_id]
amount = opts[:amount]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment