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

Ruby

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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 - Ruby

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

Solution 3 - Ruby

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 - Ruby

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

Solution 5 - Ruby

As it was said here before Rails (ActiveSupport) have a handy blank? method and it is implemented like this:

class Object
  def blank?
    respond_to?(:empty?) ? empty? : !self
  end
end

Pretty easy to add to any ruby-based project.

The beauty of this solution is that it works auto-magicaly not only for Strings but also for Arrays and other types.

Solution 6 - Ruby

variable.blank? will do it. It returns true if the string is empty or if the string is nil.

Solution 7 - Ruby

nil? can be omitted in boolean contexts. Generally, you can use this to replicate the C# code:

return my_string.nil? || my_string.empty?

Solution 8 - Ruby

First of all, beware of that method:

As Jesse Ezel says:

> Brad Abrams

> > "The method might seem convenient, but most of the time I have found that this situation arises from trying to cover up deeper bugs.

> Your code should stick to a particular protocol on the use of strings, and you should understand the use of the protocol in library code and in the code you are working with.

> The NullOrEmpty protocol is typically a quick fix (so the real problem is still somewhere else, and you got two protocols in use) or it is a lack of expertise in a particular protocol when implementing new code (and again, you should really know what your return values are)."

And if you patch String class... be sure NilClass has not been patch either!

class NilClass
    def empty?; true; end
end

Solution 9 - Ruby

Every class has a nil? method:

if a_variable.nil?
    # the variable has a nil value
end

And strings have the empty? method:

if a_string.empty?
    # the string is empty
}

Remember that a string does not equal nil when it is empty, so use the empty? method to check if a string is empty.

Solution 10 - Ruby

Another option is to convert nil to an empty result on the fly:

(my_string||'').empty?

Solution 11 - Ruby

Konrad Rudolph has the right answer.

If it really bugs you, monkey patch the String class or add it to a class/module of your choice. It's really not a good practice to monkey patch core objects unless you have a really compelling reason though.

class String
  def self.nilorempty?(string)
    string.nil? || string.empty?
  end
end

Then you can do String.nilorempty? mystring

Solution 12 - Ruby

Check for Empty Strings in Plain Ruby While Avoiding NameError Exceptions

There are some good answers here, but you don't need ActiveSupport or monkey-patching to address the common use case here. For example:

my_string.to_s.empty? if defined? my_string

This will "do the right thing" if my_string is nil or an empty string, but will not raise a NameError exception if my_string is not defined. This is generally preferable to the more contrived:

my_string.to_s.empty? rescue NameError

or its more verbose ilk, because exceptions should really be saved for things you don't expect to happen. In this case, while it might be a common error, an undefined variable isn't really an exceptional circumstance, so it should be handled accordingly.

Your mileage may vary.

Solution 13 - Ruby

If you are using rails, you can use #present?

require 'rails'

nil.present?  # ==> false (Works on nil)
''.present?    # ==> false (Works on strings)
'  '.present?  # ==> false (Works on blank strings)
[].present?    # ==> false(Works on arrays)
false.present? # ==> false (Works on boolean)

So, conversely to check for nil or zero length use !present?

!(nil.present?)  # ==> true
!(''.present?)    # ==> true
!('  '.present?)  # ==> true
!([].present?)    # ==> true
!(false.present?) # ==> true

Solution 14 - Ruby

Have you tried Refinements?

module Nothingness
  refine String do
    alias_method :nothing?, :empty?
  end

  refine NilClass do
    alias_method :nothing?, :nil?
  end
end

using Nothingness

return my_string.nothing?

Solution 15 - Ruby

For code golfers:

if my_string=~/./
  p 'non-empty string'
else
  p 'nil or empty string'
end

Or if you're not a golfer (requires ruby 2.3 or later):

if my_string&.size&.positive?
  # nonzero? also works
  p 'non-empty string'
else
  p 'nil or empty string'
end

Solution 16 - Ruby

In rails you can try #blank?.

Warning: it will give you positives when string consists of spaces:

nil.blank? # ==> true
''.blank? # ==> true
'  '.blank? # ==> true
'false'.blank? # ==> false

Just wanted to point it out. Maybe it suits your needs

UPD. why am i getting old questions in my feed? Sorry for necroposting.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJim FioratoView Question on Stackoverflow
Solution 1 - RubyEzranView Answer on Stackoverflow
Solution 2 - RubyAvdiView Answer on Stackoverflow
Solution 3 - RubyVinay SahniView Answer on Stackoverflow
Solution 4 - RubyRômulo CecconView Answer on Stackoverflow
Solution 5 - RubyHonzaView Answer on Stackoverflow
Solution 6 - RubySatya KalluriView Answer on Stackoverflow
Solution 7 - RubyKonrad RudolphView Answer on Stackoverflow
Solution 8 - RubyVonCView Answer on Stackoverflow
Solution 9 - RubyPaige RutenView Answer on Stackoverflow
Solution 10 - RubymahemoffView Answer on Stackoverflow
Solution 11 - RubyjcobyView Answer on Stackoverflow
Solution 12 - RubyTodd A. JacobsView Answer on Stackoverflow
Solution 13 - RubyDhivya DandapaniView Answer on Stackoverflow
Solution 14 - RubyRichOrElseView Answer on Stackoverflow
Solution 15 - RubysnipsnipsnipView Answer on Stackoverflow
Solution 16 - RubyNondvView Answer on Stackoverflow