Skip to content

Instantly share code, notes, and snippets.

@wjlroe
Created August 12, 2013 14:56
Show Gist options
  • Save wjlroe/6211533 to your computer and use it in GitHub Desktop.
Save wjlroe/6211533 to your computer and use it in GitHub Desktop.
class NullObject
def method_missing(*args, &block)
self
end
def nil?; true; end
end
def Maybe(value)
value.nil? ? NullObject.new : value
end
foo = nil
buz = nil
Maybe(foo).bar.baz + buz
# => #<NullObject:0x007fad649f68c0>
@wjlroe
Copy link
Author

wjlroe commented Aug 12, 2013

Breaks however, if Maybe(foo).bar returns a real object and that object doesn't respond to #baz then you get NoMethodException rather than your intended nil

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