2012-02-08 164 views
3

是否有一個好的庫(最好是寶石)做類的對象檢查?難點在於我不僅要檢查簡單對象的類型,而且還想檢查數組或哈希(如果有),並檢查其組件的類。舉例來說,如果我有一個對象:類(類型)檢查

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

我希望能夠檢查各種層次的細節,如果有類不匹配的話,我希望它返回一些合理的方式的位置。我還沒有誤差(類不匹配)的格式應該是這樣一個清晰的思路,但這樣的事情:

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]) 

如果不存在這樣的庫,可有人(告訴我在哪個方向我應該)執行這個?可能我應該使用kind_of?和遞歸定義。

回答

7

下面是一些你可以開始與

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 

它將返回true如果類匹配和false否則。

指數計算丟失。

+0

我知道我對於返回值的建議沒有完全指定。這就是我爲什麼要求提出建議的原因。 – sawa 2012-02-08 22:17:23

+0

@sawa:對不起,沒有仔細閱讀。 – 2012-02-08 22:19:44

6

is_a? or kind_of?做你在問什麼......雖然你似乎已經知道(?)。

+0

我想我可能會實現它,但如果已經有類似的事情,我不想重新發明輪子。我對此沒有那麼自信。並且還希望提供關於錯誤格式(返回值)應該如何的建議。 – sawa 2012-02-08 22:15:10