5

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?

akim
  • 8,255
  • 3
  • 44
  • 60
juliangonzalez
  • 4,231
  • 2
  • 37
  • 47

2 Answers2

2

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]
juliangonzalez
  • 4,231
  • 2
  • 37
  • 47
  • Check this https://stackoverflow.com/questions/3028243/check-if-ruby-object-is-a-boolean, I'd say it's a cleaner approach (and I bet it's faster since it does not need to create strings). Also, `blank?` is not actually defined on `true` and `false` by Ruby, Rails adds that method (justo to clarify, since your question says it's a ruby gotcha but it's actually not ruby's). EDIT: I missed you wanted to detect 0 and 1 as set too, this won't work for that – arieljuod Sep 07 '18 at 03:18
2

[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 
David Hempy
  • 5,373
  • 2
  • 40
  • 68
  • Good point, @ÁkosVandra . OP isn't looking for this to work on arrays or hashes...just '' , nil, false, and true. But thinking about your comment, I feel more strongly the `is_set()` suggestion in my answer is probably the best solution. It will cover *all* cases OP needs, including exceptional things. (like arrays and hashes or weirder stuff than that.) – David Hempy Feb 03 '20 at 15:26
  • The only not included case no longer works either: white strings (such as `" \n\t \t\n ".blank?`) will now report to be set. – Pelle May 24 '22 at 14:05