Created
April 11, 2011 14:21
-
-
Save mark/913594 to your computer and use it in GitHub Desktop.
Detecting unspecified arguments in Ruby, inspired by http://www.harukizaemon.com/2011/04/detecting-unspecified-method-arguments-in-ruby.html
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
class Object | |
def default! | |
@__is_default = true | |
self | |
end | |
def default? | |
@__is_default | |
end | |
end | |
def my_method(param = nil.default!) | |
puts "Parameter = #{ param.inspect }, is default? #{ !!(param.default?) }" | |
end | |
# With a real argument: | |
my_method 123 # => Parameter = 123, is default? false | |
# With a real nil argument: | |
my_method nil # => Parameter = nil, is default? false | |
# With no argument: | |
my_method # => Parameter = nil, is default? true | |
# PROBLEM WITH THIS IMPLEMENTATION: | |
# Call with a real nil argument again: | |
my_method nil # => Parameter = nil, is_default? true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Of course, using a proxy runs into problems with passing that proxied object into other methods that check for default-ness.