Testing for empty or nil-value string
Ruby on-RailsRubyRuby on-Rails Problem Overview
I'm trying to set a variable conditionally in Ruby. I need to set it if the variable is nil or empty (0 length string). I've come up with the following:
variable = id if variable.nil? || (!variable.nil? && variable.empty?)
While it works, it doesn't seem very Ruby-like to me. Is the a more succinct way of expressing the above?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
The second clause does not need a !variable.nil?
check—if evaluation reaches that point, variable.nil
is guaranteed to be false (because of short-circuiting).
This should be sufficient:
variable = id if variable.nil? || variable.empty?
If you're working with Ruby on Rails, Object.blank?
solves this exact problem:
> An object is blank if it’s false, empty, or a whitespace string. For example, ""
, " "
, nil
, []
, and {}
are all blank.
Solution 2 - Ruby on-Rails
If you're in Rails, .blank?
should be the method you are looking for:
a = nil
b = []
c = ""
a.blank? #=> true
b.blank? #=> true
c.blank? #=> true
d = "1"
e = ["1"]
d.blank? #=> false
e.blank? #=> false
So the answer would be:
variable = id if variable.blank?
Solution 3 - Ruby on-Rails
variable = id if variable.to_s.empty?