How to check if a variable is a number or a string?

Solution 1:

There are several ways:

>> 1.class #=> Fixnum
>> "foo".class #=> String
>> 1.is_a? Numeric #=> true
>> "foo".is_a? String #=> true

Solution 2:

class Object
  def is_number?
    to_f.to_s == to_s || to_i.to_s == to_s
  end
end

> 15.is_number?
=> true
> 15.0.is_number?
=> true
> '15'.is_number?
=> true
> '15.0'.is_number?
=> true
> 'String'.is_number?
=> false

Solution 3:

var.is_a? String

var.is_a? Numeric

Solution 4:

The finishing_moves gem includes a String#numeric? method to accomplish this very task. The approach is the same as installero's answer, just packaged up.

"1.2".numeric?
#=> true

"1.2e34".numeric?
#=> true

"1.2.3".numeric?
#=> false

"a".numeric?
#=> false