2011-06-11 73 views
2

如何創建這樣的方法:如何檢查ruby中的類屬性?

def process_by_type *things 

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

     when Array 

     when Hash 

     end 

    end 
    } 
end 

我知道我可以使用kind_of(陣列)等,但我認爲這將是更清潔,而且我不能」爲它找到一個方法的類:對象文檔頁面。

+0

如果你可以使用kind_of或is_a,這絕對是更好地使用它們。 – Spyros 2011-06-11 16:57:46

+0

爲什麼?我沒有看到任何危險。 – 2011-06-11 17:00:40

+0

只是因爲沒有重新發明輪子的意義,而且這些方法已被廣泛使用和測試。 – Spyros 2011-06-11 17:05:38

回答

3

使用情況說明的形式就像你在做什麼:

case obj 
    when expr1 
    # do something 
    when expr2 
    # do something else 
end 

相當於執行了一堆如果expr === OBJ(三重等於比較)。當expr是類類型時,如果obj是表達式表達式的一個子類型,則===比較返回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 
+0

啊,非常感謝!我曾見過這樣的事情,並認爲它有一些神祕感,但現在我明白了! – 2011-06-11 17:05:03

3

嘗試.class

>> a = "12" 
=> "12" 
>> a.class 
=> String 
>> b = 42 
=> 42 
>> b.class 
=> Fixnum