Swift style conditionals in Ruby

The Swift programming language has a neat feature that guarantees the presence of optional values in conditionals.

This method of exacting the optional value into a local constant for use inside the conditional state is a first class construct.

In Ruby you can use these same constructs to a similar effect, although there are pitfalls to using this pattern. You can assign to variables in the conditional check, however, unlike Swift, in Ruby you can only declare throwaway variables, which opens up the possibility of the value mutating later in the code. The new name variable also exists outside the scope of the conditional, polluting the namespace.

In Ruby

Using Tap

A Ruby solution to this would wrap the conditional in a block, that would provide the variable to only the block. Object#tap does exactly this, but unfortunately, this approach does not protect us from the possibleName being nil, so we'd still need to check that possibleName has a value.

Write your own

Because Ruby is the awesome language that it is, we can extend the behaviour of the Object class. Here, I've defined an Object#plug method, like Object#tap it yields itself to the supplied block, unlike Object#tap, it won't yield if 'self' is nil. In hindsight, a better method name could have been Object#tap!

This gets us pretty close to the swift unboxed value example. The harder part is making this temporary variable immutable, and that's a problem for another day.

About the Author

Phil Balchin is a full-time software developer at Heroku (a Salesforce company) and part-time photographer living in Guildford, Surrey, UK. Specialising in software development and photography, Phil also writes about graphic design, personal productivity, and travel.

facebook.com/phil.balchin | instagram.com/maniacalrobot | last.fm/users/maniacalrobot | picfair.com/maniacalrobot | maniacalrobot.tumblr.com | twitter.com/maniacalrobot
© 2011–2021 Philip Balchin | About | Colophon | RSS