Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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

like image 702
Leem.fin Avatar asked Dec 23 '11 12:12

Leem.fin


People also ask

How do you check if a variable is a string or number in Python?

We can easily use an isinstance method to check if a variable is a number or string is using an isinstance() method. Isinstance method() is a built-in method in python which returns true when the specified object is an instance of the specified type otherwise it will return false.

Can a variable be a string and a number?

The answer to your question is "no". A number can have one of several C types (e.g. int , double , ...), but only one of them, and string is not a numeric type.


4 Answers

There are several ways:

>> 1.class #=> Fixnum
>> "foo".class #=> String
>> 1.is_a? Numeric #=> true
>> "foo".is_a? String #=> true
like image 58
Michael Kohl Avatar answered Oct 20 '22 06:10

Michael Kohl


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
like image 44
installero Avatar answered Oct 20 '22 08:10

installero


var.is_a? String

var.is_a? Numeric
like image 18
Christoph Geschwind Avatar answered Oct 20 '22 06:10

Christoph Geschwind


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
like image 5
Frank Koehl Avatar answered Oct 20 '22 08:10

Frank Koehl