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
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.
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).
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.
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.
string = "" unless string.to_s.strip.empty? # ... end
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With