ruby 类(类型)检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9202107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:45:41  来源:igfitidea点击:

Class (Type) checking

rubyclassruby-1.9.3

提问by sawa

Is there a good library (preferably gem) for doing class checking of an object? The difficult part is that I not only want to check the type of a simple object but want to go inside an array or a hash, if any, and check the classes of its components. For example, if I have an object:

是否有一个好的库(最好是 gem)来进行对象的类检查?困难的部分是我不仅想检查一个简单对象的类型,而且想进入一个数组或散列(如果有),并检查其组件的类。例如,如果我有一个对象:

object = [
  "some string",
  4732841,
  [
    "another string",
    {:some_symbol => [1, 2, 3]}
  ],
]

I want to be able to check with various levels of detail, and if there is class mismatch, then I want it to return the position in some reasonable way. I don't yet have a clear idea of how the error (class mismatch) format should be, but something like this:

我希望能够检查各种级别的细节,如果存在类不匹配,那么我希望它以某种合理的方式返回位置。我还不清楚错误(类不匹配)格式应该如何,但类似这样:

object.class_check(Array) # => nil (`nil` will mean the class matches)
object.class_check([String, Fixnum, Array]) # => nil
object.class_check([String, Integer, Array]) # => nil
object.class_check([String, String, Array]) # => [1] (This indicates the position of class mismatch)
object.class_check([String, Fixnum, [Symbol, Hash]) # => [2,0] (meaning type mismatch at object[2][0])

If there is no such library, can someone (show me the direction in which I should) implement this? Probably, I should use kind_of?and recursive definition.

如果没有这样的库,有人可以(向我展示我应该遵循的方向)实现这个吗?也许,我应该使用kind_of?递归定义。

回答by Ed S.

is_a?or kind_of?do what you are asking for... though you seem to know that already(?).

is_a?或者kind_of?做你所要求的......虽然你似乎已经知道了(?)。

回答by undur_gongor

Here is something you can start with

你可以从这里开始

class Object
  def class_check(tclass)
    return self.kind_of? tclass unless tclass.kind_of? Array
    return false unless self.kind_of? Array
    return false unless length == tclass.length
    zip(tclass).each { | a, b | return false unless a.class_check(b) }
    true
  end
end

It will return trueif the classes match and falseotherwise.

true如果类匹配,false则返回,否则返回。

Calculation of the indices is missing.

缺少指数的计算。