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
Ruby 2.3.0 added a safe navigation operator (
&.
) that checks for nil before calling a method.It will return
nil
ifs
isnil
, rather than raisingNoMethodError
.ActiveSupport
comes with a method for that :try
. For example,an_object.try :strip
will returnnil
ifan_object
is nil, but will proceed otherwise. The syntax is the same assend
. Cf active_support_core_extensions.html#try.You could simply do this
If you don't mind the extra object being created, either of these work:
Without extra object: