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

ruby

Is there a better way than the following to check to see if a string is nil OR has a length of 0 in Ruby?

if !my_string || my_string.length == 0
  return true
else
  return false
end

In C# there's the handy

string.IsNullOrEmpty(myString)

Anything similar to that in Ruby?

Best Answer

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