How Do You Test If a Variable Is a String or a Numeric Data Type in Ruby?

Problem scenario
You want to test if a given variable is a Numeric or String.  These are built-in data types that Ruby has.

What should you do?

Solution
Append ".is_a? Numeric" or ".is_a? String" to variable.  For an example, here is code that explicitly prints out if the data type is a Numeric or String.

var1 = 123
an = var1.is_a? Numeric
as = var1.is_a? String
puts "var1 is a numeric: " + (an ? "true" : "false")
puts "var1 is a string: " + (as ?  "true" : "false")
puts "---Now for a new variable---"
var2 = 'continual'
bn = var2.is_a? Numeric
bs = var2.is_a? String
puts "var2 is a numeric: " + (bn ? "true" : "false")
puts "var2 is a string: " + (bs ? "true" : "false")

Leave a comment

Your email address will not be published.