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

前端 未结 7 1611
礼貌的吻别
礼貌的吻别 2020-12-13 11:59

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

相关标签:
7条回答
  • 2020-12-13 12:39
    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
    
    0 讨论(0)
  • 2020-12-13 12:40
    var.is_a? String
    
    var.is_a? Numeric
    
    0 讨论(0)
  • 2020-12-13 12:43

    There are several ways:

    >> 1.class #=> Fixnum
    >> "foo".class #=> String
    >> 1.is_a? Numeric #=> true
    >> "foo".is_a? String #=> true
    
    0 讨论(0)
  • 2020-12-13 12:48
    if chr.to_i != 0
      puts "It is number,  yep"
    end
    
    0 讨论(0)
  • 2020-12-13 12:51

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

    e.g.:

    puts varName.class
    
    0 讨论(0)
  • 2020-12-13 12:53
    class Object
      def numeric?
        Float(self) != nil rescue false
      end
    end
    
    0 讨论(0)
提交回复
热议问题