Skip to content

Instantly share code, notes, and snippets.

@araipiyo
Created June 14, 2014 08:14
Show Gist options
  • Save araipiyo/56ee0b202db24e42da66 to your computer and use it in GitHub Desktop.
Save araipiyo/56ee0b202db24e42da66 to your computer and use it in GitHub Desktop.
maybe for Ruby. easier handling of nil. nil is most bothersome thing in Ruby, right?
require 'singleton'
class Object
def maybe
if self.class == NilClass
Maybe.instance
else
self
end
end
end
class NilClass
def id
nil
end
end
class Maybe
include Singleton
def method_missing(m, *args, &block)
self
end
def respond_to_missing?(*_)
true
end
def inspect
"maybe"
end
def ==(a)
if a.class == NilClass
true
elsif a.class == Maybe
true
else
false
end
end
def id
nil
end
def to_s
""
end
def to_i
0
end
def to_f
0.0
end
def to_a
[]
end
def blank?
true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment