【问题标题】:Function to find object type in Ruby在 Ruby 中查找对象类型的函数
【发布时间】:2016-04-14 14:02:27
【问题描述】:

我想知道是否有任何ruby函数或方法可以找出对象的类型(IntegerStringSymbol等)。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    您所做的假设是,如果数学运算返回的值是整数,则该值的类将为 Fixnum。这是不正确的。

    看看:

    a = 5
    puts a.class
    # => Fixnum
    
    b = 5.0
    puts b.class
    # => Float
    

    从数学上讲,5 和 5.0 是同一个数字,而这个数字是一个整数。但是 Ruby 中的 5 和 5.0(与许多其他编程语言一样)并不相同。一个是fixed-point 值(ergo Fixnum),另一个是floating-point 值(浮点数)。 Fixnum 只能表示整数,但 Float 可以同时表示整数和分数(但是,我应该提一下,not all fractions)。

    在 Ruby 中,当您对两个 Fixnum 进行数学运算时,会返回一个 Fixnum:

    a = 4
    puts a.class # => Fixnum
    
    x = a ** 2
    puts x       # => 16
    puts x.class # => Fixnum
    

    但是,如果任一数字是浮点数,则返回浮点数:

    a = 4
    
    x = a ** 2.0
    puts x       # => 16.0
    puts x.class # => Float
    
    b = 4.0
    puts b.class # => Float
    
    y = b ** 2
    puts y       # => 16.0
    puts y.class # => Float
    
    y = b ** 2.0
    puts y       # => 16.0
    puts y.class # => Float
    

    您询问了如何“查找对象的类型”,该问题的答案是使用Object#class 方法,如上所述。但正如您所见,“对象是 Fixnum 吗?”和“对象是整数吗?”是两个不同的问题。

    如果您想知道 Ruby 中的数字是否为整数,即使它是浮点数,请参阅此问题的优秀答案:Checking if a Float is equivalent to an integer value in Ruby

    【讨论】:

      【解决方案2】:

      你可以在对象上调用class method

      obj.class
      

      对于实例

      :test_1.class => Symbol
      

      或者你也可以使用:instance_of? Method

      puts 10.instance_of? Fixnum    #=> True
      puts [1,2].instance_of? Array  #=> True
      

      更多信息你可以determining-type-of-an-object-in-ruby看到这个

      【讨论】:

        【解决方案3】:

        42Fixnum 的实例,FixnumNumeric 的子类。 4.2Float 的实例,Float 也是Numeric 的子类。

        42.kind_of? Numeric
        => true
        
        (4.2).kind_of Numeric
        => true
        

        【讨论】:

          猜你喜欢
          • 2010-09-25
          • 2011-10-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-01
          相关资源
          最近更新 更多