Created
April 15, 2013 19:55
-
-
Save rdp/5390849 to your computer and use it in GitHub Desktop.
Required named parameters snippet, gleaned from http://stackoverflow.com/questions/13250447/can-i-have-required-named-parameters-in-ruby-2-x
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 required(arg=nil) | |
method = caller_locations(1,1)[0].label | |
raise ArgumentError.new("required parameter #{arg.to_sym.inspect + ' ' if arg}not passed to method #{method}") | |
end | |
def say(greeting: required('greeting')) | |
puts greeting | |
end | |
def say2(greeting: required) | |
puts greeting | |
end | |
def say3(greeting: required(:greeting)) | |
puts greeting | |
end | |
# say | |
# test.rb:3:in `required': required parameter :greeting not passed to method say (ArgumentError) | |
# from test.rb:6:in `say' | |
# from test.rb:18:in `<main>' | |
# say2 | |
# test.rb:3:in `required': required parameter not passed to method say2 (ArgumentError) | |
# from test.rb:10:in `say2' | |
# from test.rb:23:in `<main>' | |
# say3 | |
#test.rb:3:in `required': required parameter :greeting not passed to method say3 (ArgumentError) | |
# from test.rb:14:in `say3' | |
# from test.rb:28:in `<main>' | |
# calling it like say('greeting') results in ArgumentError | |
say greeting: 'greeting' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment