andand 0

The Maybe Monad in idiomatic Ruby

h1. Object#andand

h2. What

@Object#[email protected] lets us write:

@phone = Location.find(:first, ...elided... )
And get a _guarded method invocation_ or _safe navigation method_. This snippet performs a @[email protected] on the Location class, then sends @[email protected] to the result _if the result is not nil_. If the result is nil, then the expression returns nil without throwing a NoMethodError. As Dejan Simic "put it": Why would you want to write this:'description') &&'description').inner_text
when you can write this:'description').andand.inner_text
Why indeed! As a bonus, install andand and you will also receive an enhanced Object#tap method, _at no extra charge_! h2. Installing Update to RubyGems 1.2.0 before proceeding!!
sudo gem sources -a (you only have to do this once)
sudo gem install raganwald-andand


git clone git://
cd andand
rake gem
rake install_gem

h2. The basics

h3. Object#andand

Ruby programmers are familiar with the two guarded assignment operators @&&[email protected] and @||[email protected] The typical use for them is when you have a variable that might be nil. For example:

first_name &&= @first_name.trim
@phone ||= '612-777-9311'
You are trimming the first name provided it isn’t nil, and you are assigning ‘612-777-9311’ to the phone if it _is_ nil (or false, but that isn’t important right now). The other day we were discussing the guards and we agreed that we wished there was a _guarded method invocation_ operator. Here’s an example of when you would use it:
@phone = Location.find(:first, ...elided... )&&.phone
Meaning, search the location table for the first record matching some criteria, and if you find a location, get its phone. If you don’t, get nil. (Groovy provides this exact functionality, although Groovy uses @[email protected] instead of @[email protected]) However, @[email protected] won’t work because @[email protected] is not a real Ruby operator. Object#andand let’s us write:
@phone = Location.find(:first, ...elided... )
And get the same effect as:
@phone = ->(loc){ loc && }.call(Location.find(:first, ...elided... ))
Note that because you accept any method using Ruby’s method invocation syntax, you can accept methods with parameters and/or blocks:
list_of_lists.detect { ...elided... }.andand.inject(42) { ...elided ... }
Object#andand emphasizes syntactic regularity: the goal was to make an @[email protected] operation that worked like @[email protected] @[email protected] looks just like normal assignment, you can use any expression on the RHS, only the semantics are different. The andand method also works just like a normal method invocation, only the semantics are modified. h3. Block-Structured andand You can use @[email protected] with a block instead of a method:
@phone =  Location.find(:first, ...elided... ).andand { |location|
If the receiver is nil, the block is not executed and @[email protected] returns @[email protected] If the receiver is not nil, it is passed as a parameter to the block and @[email protected] returns the value of the block. This makes it possible to perform conditional evaluation and also to make the scope of the variable really obvious. h3. Scope @Object#[email protected] only works for one method call. For example, @[email protected] is going to call @[email protected] if @[email protected] is @[email protected] That's because @[email protected] is going to evaluate to @[email protected], and then we will call the method @[email protected] on it. In most cases, you want to use @[email protected] If that seems awkward, you might want to reconsider violating the Law of Demeter in an environment where you can't be sure if your receiver is @[email protected] or not. Another example of this (pointed out by Jan Zimmek):
x = nil
x.andand.length > 3
This results in a @[email protected] Again, @[email protected] is @[email protected], therefore @[email protected] is @[email protected], therefore we end up with @nil > [email protected] which results in a @[email protected] This can be fixed with @x.andand.length.andand > [email protected] as above, or perhaps:
x = nil
x.andand { |value| value.length > 3 }

h3. Enhanced Object#tap

Ruby 1.9 introduces “Object#tap”: This library implements Object#tap for Ruby 1.8 and enhances it. As in Ruby 1.9, you can call @[email protected] with a block:

	blah.sort.grep( /foo/ ).tap { |xs| p xs }.map { |x| x.blah }
But like its sibling @[email protected], you can now call @[email protected] with a method as well:
	[1, 2, 3, 4, 5] { |n| n * 2 }
    	=> [2, 4, 6, 8]

h3. Doctor, it hurts when I do that

So don’t do that!

The popular use case for Object#tap is poor man’s debugging:

	blah.sort.grep( /foo/ ).tap { |xs| p xs }.map { |x| x.blah }
Perhaps you want to remove the tap, you can delete it:
	blah.sort.grep( /foo/ ).map { |x| x.blah }
Or, you can change it to @[email protected]:
	blah.sort.grep( /foo/ ).dont { |xs| p xs }.map { |x| x.blah }
Like @[email protected] and @[email protected], @[email protected] works with arbitrary methods, not just blocks:
	    => [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
	    => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

h2. A little more background

“Object#andand & Object#me in Ruby”: explains the original motivations, as well as providing links to similar implementations you may want to consider. A few people have pointed out that Object#andand is similar to Haskell’s Maybe monad. “The Maybe Monad in Ruby”: is a good introduction for Ruby programmers.

h2. That’s cool, but…

No problem, I get that andand isn’t exactly what you need. Have a look at the “Invocation Construction Kit”: or “Ick.” The Ick gem generalizes #andand and #tap: Ick provides four useful ways to block-structure your code, the methods #let, #returning, #inside, and #my. Ick also includes four quasi-monadic invocations, #maybe, #please, #tee, and #fork.

“Ick”: provides abstractions for building your own invocations, so you can branch out and build some of your own abstractions with Ick’s building blocks.

h2. How to submit patches

Read the “8 steps for fixing other people’s code”:

The public clone url is @git://[email protected] Fork you very much.

h2. License

This code is free to use under the terms of the “MIT license”:

h2. Shout Out

“Mobile Commons”: Huge.

Also interesting: “Wicked”:

h2. Contact

Comments are welcome. Send an email to “Reginald Braithwaite”:mailto:[email protected]

Related Repositories



The Maybe Monad in idiomatic Ruby ...



RewriteRails adds syntactic abstractions like Andand and String to Block to Rails projects without monkey-patching ...



Wicked Good extensions to Object in the vein of #andand ...



The Maybe Monad in idiomatic Ruby ...



The Maybe Monad in idiomatic Ruby ...

Top Contributors

raganwald archiloque foobear panozzaj