Last active
October 12, 2015 14:08
-
-
Save garethrees/4038774 to your computer and use it in GitHub Desktop.
Hash arguments, default values and asserting valid keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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