---
title: Swallow Nil
teaser:
tags: web,ruby,good code
author: Dan Croak
published_on: 2009-09-18
---

I've been using this for [about a year and a half](http://dancroak.tumblr.com/post/31279957/swallow-nil).

Abomination or legitimate tool for the box?

## Usage

> two dots or more. nil anywhere in the chain is an acceptable response.

    campaign = swallow_nil { supporter.politician.campaign }

## Definition

    def swallow_nil
      yield
    rescue NoMethodError
      nil
    end

## try()

It's similar to
[try](http://railsapi.com/doc/rails-v2.3.4/classes/Object.html#M006206) from
ActiveSupport except for chains instead of individual methods.

## Law of Demeter

Are you strict about Law of Demeter violations?

Or, do you find yourself with occasional chains like this that could benefit
from `swallow_nil()` or `try()` or `andand()`?
