Jim Fiorato
Jim Fiorato

Reputation: 4872

Is There a Better Way of Checking Nil or Length == 0 of a String in 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?

Upvotes: 178

Views: 130894

Answers (16)

Dhivya Dandapani
Dhivya Dandapani

Reputation: 431

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

Upvotes: 2

snipsnipsnip
snipsnipsnip

Reputation: 2585

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

Upvotes: 0

Ezran
Ezran

Reputation: 2847

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

Upvotes: 234

RichOrElse
RichOrElse

Reputation: 139

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?

Upvotes: 1

Nondv
Nondv

Reputation: 819

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.

Upvotes: 0

mahemoff
mahemoff

Reputation: 46409

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

(my_string||'').empty?

Upvotes: 4

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84353

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.

Upvotes: 2

Vinay Sahni
Vinay Sahni

Reputation: 5053

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 == ""

Upvotes: 67

Satya Kalluri
Satya Kalluri

Reputation: 5214

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

Upvotes: 15

Honza
Honza

Reputation: 4409

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.

Upvotes: 31

Avdi
Avdi

Reputation: 18418

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

Upvotes: 73

VonC
VonC

Reputation: 1324437

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

Upvotes: 7

Rômulo Ceccon
Rômulo Ceccon

Reputation: 10347

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

Upvotes: 32

jcoby
jcoby

Reputation: 4260

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

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545598

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

return my_string.nil? || my_string.empty?

Upvotes: 13

Paige Ruten
Paige Ruten

Reputation: 176665

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.

Upvotes: 4

Related Questions