Ruby on rails 如何检查ruby中属性的类类型?

Ruby on rails 如何检查ruby中属性的类类型?,ruby-on-rails,ruby,Ruby On Rails,Ruby,如何创建如下方法: def process_by_type *things things.each {|thing| case thing.type when String when Array when Hash end end } end 我知道我可以使用某种?(数组)等,但我认为这样会更干净,而且我在类:对象文档页面上找不到它的方法。试试: 使用案例陈述的形式,如您所做的: case obj when

如何创建如下方法:

def process_by_type *things

  things.each {|thing|
    case thing.type
      when String

      when Array

      when Hash

      end

    end
  }
end
我知道我可以使用某种?(数组)等,但我认为这样会更干净,而且我在类:对象文档页面上找不到它的方法。

试试:


使用案例陈述的形式,如您所做的:

case obj
  when expr1
    # do something
  when expr2
    # do something else
end
相当于执行一系列if expr===obj(三重等于比较)。当expr是类类型时,如果obj是expr的类型或expr的子类,则===比较返回true

因此,以下内容应满足您的期望:

def process_by_type *things

  things.each {|thing|
    case thing
      when String
        puts "#{thing} is a string"
      when Array
        puts "#{thing} is an array"
      when Hash
        puts "#{thing} is a hash"
      else
        puts "#{thing} is something else"
    end
  }
end

如果你能用一种或是一种,那么使用它们肯定会更好。为什么?我看不出有什么危险。只是因为重新发明轮子没有意义,而且这些方法已经被广泛使用和测试。通常最好检查对象支持什么方法(duck类型),而不是检查它的类层次结构是什么。这样,代码的用户就可以使用自己的自定义类,而不必被迫进入特定的继承层次结构。例如,您可以检查某个对象是整数(respond_to?:to_int)还是可转换为整数(respond_to?:to_i),而不是检查类型(obj.kind_of?(Integer)或Integer==obj)。啊,非常感谢!我曾经看到过这样的东西,还以为它有点神秘,但现在我明白了!!
def process_by_type *things

  things.each {|thing|
    case thing
      when String
        puts "#{thing} is a string"
      when Array
        puts "#{thing} is an array"
      when Hash
        puts "#{thing} is a hash"
      else
        puts "#{thing} is something else"
    end
  }
end