Reputation: 4381
I need to check on a Boolean variable whether its value has been set or not, I would know that by checking if it contains an empty string ""
or nil
indicates the value has not been set and another value as true
or false
indicates the value has been set.
I tried using blank?
but Rails has this gotcha on the blank?
method that when called on false
will actually return true
false.blank? # Returns true
So, when the value of the variable had been set to false, it would give me false negatives for the value as if the variable wouldn't have been set.
How to check that a variable is not set(""
, nil
) or it is set(true
,false
, 0
, 1
) in Ruby on Rails?
Upvotes: 6
Views: 2595
Reputation: 1
Glad to came across this topic today I was struggling with the
false.blank? # Returns true
and for me this was the answer what I was looking for.
my_var.to_s.empty?
Following the idea I was digging a bit to understand why false.blank? it is true and I found the documentation about it
and I will keep with the comment of wale on this thread discuss.rubyonrails "While the word may mean different things to each of us, the “correct” meaning is what’s defined in the docs."
Happy coding.
Upvotes: 0
Reputation: 4381
I found the easiest way is to call .to_s
on the variable before calling blank?
> ["", '', nil, false,true, 0, 1].map{|val| val.to_s.blank?}
# => [true, true, true, false, false, false, false]
Upvotes: 2
Reputation: 6247
[Edited to give this solution first]: I think the best solution is to be explicit about it:
def not_set?(x)
[nil, ''].include?(x)
end
This will be more performant than converting to strings, is clearly understandable to all, and covers unknown surprise input in the future.
And here was my original solution, briefer, ruby-er, but less performant and less robust:
Try my_var.to_s.empty?
I believe that covers all six cases you're interested in:
puts " show unset (nil, '') "
puts ''.to_s.empty?
puts nil.to_s.empty?
puts " show set (true, false, 0, 1) "
puts true.to_s.empty?
puts false.to_s.empty?
puts 0.to_s.empty?
puts 1.to_s.empty?
Yields:
show unset (nil, '')
true
true
show set (true, false, 0, 1)
false
false
false
false
Upvotes: 3