I have a string in Ruby on which I'm calling the strip method to remove the leading and trailing whitespace. e.g.
s = "12345 "
s.strip
However if the string is empty I get the following error.
NoMethodError: undefined method `strip' for nil:NilClass
I'm using Ruby 1.9 so whats the easiest way to check if the value is nil before calling the strip method?
Update:
I tried this on an element in an array but got the same problem:
data[2][1][6].nil? ? data[2][1][6] : data[2][1][6].split(":")[1].strip
If you want to avoid the error that appears in the question:
I'd opt for a solution where
s
can never benil
to start with.You can use the
||
operator to pass a default value ifsome_method
returns a falsy value:Or if
s
is already assigned you can use||=
which does the same thing:Providing default scenario's for the absence of a parameters or variables is a good way to keep your code clean, because you don't have to mix logic with variable checking.
Method which works for me (I know, I should never pollute pristine
Object
space, but it's so convenient that I will take a risk):In your particular case it could be:
data[2][1][6].unless_nil { |x| x.split(":")[1].unless_nil(&:strip) }
You can use method
try
from ActiveSupport (Rails library)or you can use my gem tryit which gives extra facilities:
I guess the easiest method would be the following:
Simply put:
Tl;dr Check if s is nil, then return s, otherwise, strip it.