Skip to content

Instantly share code, notes, and snippets.

@jcamenisch
Created June 25, 2013 04:00
Show Gist options
  • Save jcamenisch/5855837 to your computer and use it in GitHub Desktop.
Save jcamenisch/5855837 to your computer and use it in GitHub Desktop.
Return blackhole object with maybe(something), but convert blackhole back to nil with a chain-closing method. Because sometimes we need to send values to outside code that understands the nil idiom, but not our "exotic" blackhole object.
class BlackHole
def method_missing(*args, &block)
self
end
def unmaybe
nil
end
# ...
end
def maybe(thing)
thing.nil? ? BlackHole.new : thing
end
class Object
def unmaybe
self
end
end
a_thing = "A string of sorts."
maybe(a_thing)[0..5].downcase.unmaybe #=> "a stri"
a_thing = nil
maybe(a_thing)[0..5].downcase.unmaybe #=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment