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_str
variable.blank? will do it. It returns true if the string is empty or if the string is nil.
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.
Another option is to convert nil to an empty result on the fly:
(my_string||'').empty?
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 == ""
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.
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?