How Do You Check If a Variable in Ruby Is a Boolean?

Problem scenario
You want to determine if a variable is being assigned a non-string "true" or "false" data type.  That is, you want to distinguish from a string value of true/false and the Boolean, built-in, supported data type of true/false.  Some programming languages support Boolean or bit values.  Ruby has a number of data types.  There is a feature that Ruby supports to test for most of its datatypes.  By appending to a variable this ".is_a?", you can test if a variable is a string, numeric, etc.  However, there is no supported way we know of for using this ".is_a?" determining if a variable is a Boolean.  What do you do?

Solution
Just assign var1 to the variable you want to check, eliminate the first line below, and run this code snippet in your program:

var1 = system("date") # System commands always return true or false values.
# Assign var1 to the variable you want to determine if it is a Boolean or not.  
as = var1.is_a? String
if as
   puts "Ruby does not consider var1 to be a Boolean"
else
   ns = as ? "true" : "false"
   if ns
        puts "Ruby considers var1 to be a Boolean"
   else
        puts "Ruby does not consider var1 to be a Boolean"
   end
end

Leave a comment

Your email address will not be published. Required fields are marked *