Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

Solution 1:

When I'm not worried about performance, I'll often use this:

if my_string.to_s == ''
  # It's nil or empty
end

There are various variations, of course...

if my_string.to_s.strip.length == 0
  # It's nil, empty, or just whitespace
end

Solution 2:

If you are willing to require ActiveSupport you can just use the #blank? method, which is defined for both NilClass and String.

Solution 3:

I like to do this as follows (in a non Rails/ActiveSupport environment):

variable.to_s.empty?

this works because:

nil.to_s == ""
"".to_s == ""

Solution 4:

An alternative to jcoby's proposal would be:

class NilClass
  def nil_or_empty?
    true
  end
end

class String
  def nil_or_empty?
    empty?
  end
end