Compacting Pesky Nils

July 30, 2015

Nils will always find a way to sneak into your code. Given an array of values, any of which may be nil (from user input or unexpected method returns among others), use Array#compact to remove all nil elements.

Heres an example of what could happen:

first = nil
middle = nil
last = "Forgetfull"

full_name = [first, middle, last].join(" ")
#=> "  Forgetfull"

Using compact will remove the unexepected spaces:

first = nil
middle = nil
last = "Forgetfull"

full_name = [first, middle, last].compact.join(" ")
#=> "Forgetfull"

At the end of the day it’s best to assume any value could potentially be nil - so it’s best to code in ways that prevents nil (either through coercion or nil removal) or risk unexepected results or worse, that pesky NoMethodError.

Comments

comments powered by Disqus