Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby way to check if a string is not blank?

Tags:

ruby

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 
like image 240
Rajkaran Mishra Avatar asked Mar 10 '16 13:03

Rajkaran Mishra


People also ask

Is empty string nil Ruby?

nil? will only return true if the object itself is nil. That means that an empty string is NOT nil and an empty array is NOT nil.

How do you check if something is nil in Ruby?

In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).

Is Empty Ruby?

empty? is a standard Ruby method on some objects like Arrays, Hashes and Strings. Its exact behaviour will depend on the specific object, but typically it returns true if the object contains no elements.

Does check for empty string?

Java String isEmpty() MethodThe isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.


2 Answers

string = ""  unless string.to_s.strip.empty?   # ... end 
like image 99
Lukas Baliak Avatar answered Sep 22 '22 11:09

Lukas Baliak


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?

like image 37
RamanSM Avatar answered Sep 21 '22 11:09

RamanSM