Leem.fin
Leem.fin

Reputation: 42582

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

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

Upvotes: 67

Views: 82429

Answers (7)

installero
installero

Reputation: 9766

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

Upvotes: 31

markhorrocks
markhorrocks

Reputation: 1398

class Object
  def numeric?
    Float(self) != nil rescue false
  end
end

Upvotes: 3

BSalunke
BSalunke

Reputation: 11727

Print its class, it will show you which type of variable is (e.g. String or Number).

e.g.:

puts varName.class

Upvotes: 2

Liker
Liker

Reputation: 2267

if chr.to_i != 0
  puts "It is number,  yep"
end

Upvotes: -4

Frank Koehl
Frank Koehl

Reputation: 3176

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

Upvotes: 5

Christoph Geschwind
Christoph Geschwind

Reputation: 2680

var.is_a? String

var.is_a? Numeric

Upvotes: 19

Michael Kohl
Michael Kohl

Reputation: 66837

There are several ways:

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

Upvotes: 102

Related Questions