Easy null object pattern in Ruby

Ever wanna chain some methods on something but want to ignore nil, without having to special-case for nil?

Edit: I actually use this quite often so I made a gem for it: https://github.com/mrbrdo/nullobject_chain

Solution 1:

And also solution without using exceptions, maybe a little more reliable because we know that NoMethodError occurs on NilClass instance:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s