Ruby way to check if a string is not blank?

What's the best way to check if a variable is not blank in an else if condition in Ruby (not Rails)?

elsif not variable.to_s.empty?
  # do something
end

or

elsif !variable.to_s.empty?
  # do something
end

or

elsif variable.to_s.length > 0
  # do something
end

Solution 1:

string = ""

unless string.to_s.strip.empty?
  # ...
end

Solution 2:

I just found out that ''.empty? returns true but ' '.empty? returns false. Even to_s.length for ' ' is not zero.

Maybe it is better to use strip as ' '.strip.empty?

Solution 3:

You can use either

unless var.empty?
  #do sth
end

or

unless var == ""
  #do sth
end

or all of these with if and a negator !.

Solution 4:

The source of the empty? method is analogous to the following:

def empty?
    return length == 0      
end 

So, you can safely use

any_string.length != 0

Anyway, using that code inside an else if is a bit verbose, I would encourage you to define the present? method inside the String class.

class String
    def present?
        !empty?
    end
end

Now you can write your code the following way:

if some_condition
  # do something
elsif variable.to_s.present?
  # do something else
end

This way you get a clear code, without using negations or unless who are hard to read.

Of course, there is one problem here, I took the present? name (and method) from Rails. present? returns true if the object is not blank, but strings with tabs or spaces (white characters) are considered blanks. So, this present? will return true to for the following strings:

"".present?       # => false
"   ".present?    # => true
"\t\n\r".present? # => true
" blah ".present? # => true

It depends on what you want, high chances are that you want to get true for the first 3 strings, and false for the later. You could use @RamanSM approach and use strip to avoid empty spaces

class String
    def present?
        !strip.empty?
    end
end

now, present? returns false for strings with white spaces

"".present?       # => false
"   ".present?    # => false
"\t\n\r".present? # => false
" blah ".present? # => true