Ruby check if nil before calling method
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 nil
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
Solution 1:
Ruby 2.3.0 added a safe navigation operator (&.
) that checks for nil before calling a method.
s&.strip
If s
is nil
, this expressions returns nil
instead of raising NoMethodError
.
Solution 2:
You can use method try
from ActiveSupport (Rails library)
gem install activesupport
require 'active_support/core_ext/object/try'
s.try(:strip)
or you can use my gem tryit which gives extra facilities:
gem install tryit
s.try { strip }
Solution 3:
If you don't mind the extra object being created, either of these work:
"#{s}".strip
s.to_s.strip
Without extra object:
s && s.strip
s.strip if s
Solution 4:
I guess the easiest method would be the following:
s.strip if s