The Maybe monad for Ruby
Latest commit 2a27bd3 Jun 26, 2012 James Ottaway Require the core of Maybe when loading `core_ext` so you don't need t…
…o require both
Failed to load latest commit information.
LICENSE Added license Mar 16, 2010


A library for treating nil and non-nil objects in a similar manner. Technically speaking, Maybe is an implemenation of the maybe monad.


The Maybe class wraps any value (nil or non-nil) and lets you treat it as non-nil.

require "maybe"
"hello".upcase                         #=> "HELLO"
nil.upcase                             #=> NoMethodError: undefined method `upcase' for nil:NilClass"hello").upcase.__value__    #=> "HELLO"        #=> nil

You can also use the method Maybe for convenience. The following are equivalent:"hello").__value__           #=> "hello"
Maybe("hello").__value__               #=> "hello"

You can also optionally patch Object to include a #maybe method:

require "maybe/core_ext"
"hello".maybe.upcase                   #=> "HELLO"

When you call with a value, that value is wrapped in a Maybe object. Whenever you call methods on that object, it does a simple check: if the wrapped value is nil, then it returns another Maybe object that wraps nil. If the wrapped object is not nil, it calls the method on that object, then wraps it back up in a Maybe object.

This is especially handy for long chains of method calls, any of which could return nil.

# foo, bar, and/or baz could return nil, but this will still work

Here's a real world example. Instead of writing this:

if(customer && customer.order &&
  # ... do something with customer

just write this:

  # ... do something with customer

If your wrapped object does not have a #value method, you can call

instead of


require "maybe""10")                    #=> A Maybe object, wrapping "10""10").to_i               #=> A Maybe object, wrapping 10"10").to_i.__value__     #=> 10                     #=> A Maybe object, wrapping nil                #=> A Maybe object, still wrapping nil      #=> nil

Related Reading

Note on Patches/Pull Requests

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so I don't break it in a future version unintentionally.
  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.


Copyright (c) 2009, 2010 Ben Brinckerhoff. See LICENSE for details.