Skip to content

Instantly share code, notes, and snippets.

@mark
Created April 11, 2011 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mark/913594 to your computer and use it in GitHub Desktop.
Save mark/913594 to your computer and use it in GitHub Desktop.
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
@brainopia
Copy link

nil is a singleton, so once you sent :default! to it, it will always return true to :default? message.

Try to change order of calls and you'll see.

@mark
Copy link
Author

mark commented Apr 11, 2011

Yeah, you're totally right... I had forgotten about that until one of my coworkers pointed it out to me. In that case, I'd probably keep the api (which I like), and instead have default! return a proxy around an object, that defines default?.

@mark
Copy link
Author

mark commented Apr 11, 2011

Of course, using a proxy runs into problems with passing that proxied object into other methods that check for default-ness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment