Skip to content

Instantly share code, notes, and snippets.

@rbxbx
Created February 9, 2011 17:38
Show Gist options
  • Select an option

  • Save rbxbx/818870 to your computer and use it in GitHub Desktop.

Select an option

Save rbxbx/818870 to your computer and use it in GitHub Desktop.
Object#maybe - A (crude?) implementation of the Maybe monad in Ruby
class BlankSlate
instance_methods.each { |m| undef_method m unless m =~ /^__/ }
end
class MaybeProxy < BlankSlate
attr_reader :obj
def initialize(obj)
@obj = obj
end
def method_missing(meth, *args, &blk)
MaybeProxy.new(obj.try(meth, *args, &blk))
end
end
class Object
def maybe(&blk)
(yield MaybeProxy.new(self)).obj
end
def try(method, *args, &block)
send(method, *args, &block) if respond_to?(method)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment