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

Ruby

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

There are several ways:

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

Solution 2 - Ruby

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 - Ruby

var.is_a? String

var.is_a? Numeric

Solution 4 - Ruby

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

Solution 5 - Ruby

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

e.g.:

puts varName.class

Solution 6 - Ruby

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

Solution 7 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeem.finView Question on Stackoverflow
Solution 1 - RubyMichael KohlView Answer on Stackoverflow
Solution 2 - RubyinstalleroView Answer on Stackoverflow
Solution 3 - RubyChristoph GeschwindView Answer on Stackoverflow
Solution 4 - RubyFrank KoehlView Answer on Stackoverflow
Solution 5 - RubyBSalunkeView Answer on Stackoverflow
Solution 6 - RubymarkhorrocksView Answer on Stackoverflow
Solution 7 - RubyLiker777View Answer on Stackoverflow