Created
June 9, 2011 20:24
-
-
Save lsantos/1017644 to your computer and use it in GitHub Desktop.
using a hash as method parameter
This file contains hidden or 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
# Use Hash#assert_valid_keys (from ActiveSupport) to document what | |
# keys to use when calling the method | |
def greet(options) | |
options.assert_valid_keys(:first_name, :last_name) | |
puts "Hello #{options[:first_name]} #{options[:last_name]}!" | |
end | |
#=> Hello Thuva Tharma! | |
greet(:first_name => "Thuva", :last_name => "Tharma") | |
#=> Unknown key(s): name (ArgumentError) | |
greet(:name => "Thuva Tharma") | |
# Do not set the default value for options like below | |
def greet(options={:first_name => "Thuva", :last_name => "Tharma"}) | |
puts "Hello #{options[:first_name]} #{options[:last_name]}!" | |
end | |
#=> Hello Thuva Tharma! | |
greet | |
#=> Hello Thuva ! (Tharma is not used as a default value) | |
greet(:first_name => "Thuva") | |
# What you really want is: | |
def greet(opts={}) | |
default_options = { | |
:first_name => "Thuva", | |
:last_name => "Tharma" | |
} | |
# Note: I'm not altering the value of opts. You should generally | |
# not change the value of arguments passed in to the method. | |
options = default_options.merge(opts) | |
puts "Hello #{options[:first_name]} #{options[:last_name]}!" | |
end | |
#=> Hello Thuva Tharma! | |
greet | |
#=> Hello Thuva Tharma! | |
greet(:first_name => "Thuva") | |
# Throw in Hash#assert_valid_keys in the last method definition | |
# above and you're golden! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment