Ruby 中的 Kind_of、Instance_of 和 Is_a
Stewart Nguyen
2023年1月30日
Ruby
Ruby Inheritance
在 Ruby 中,我們可能需要不時檢查物件型別。有幾種方法可以做到這一點,包括 is_a、kind_of 和 instance_of。
使用 is_a 檢查 Ruby 中的物件型別
讓我們從建立我們的類開始:
class Animal; end
dog = Animal.new
我們可以使用 is a? 確定 dog 的型別:
dog.is_a?(String)
# => false
dog.is_a?(Animal)
# => true
Dog 不是字串。它是 Animal 類的物件。
is_a? 方法很有趣,因為它檢查物件的當前類及其祖先。
如果物件的祖先包含與引數匹配的任何類,它將返回 true。
class Mammal < Animal; end
whale = Mammal.new
鯨魚是哺乳動物,也是自然界中的動物。在 Ruby 中是什麼樣的?
Ruby 出色地執行了必要的檢查:
whale.is_a?(Mammal)
# => true
whale.is_a?(Animal)
# => true
讓我們來看看鯨魚的祖先:
whale.class.ancestors
輸出:
=> [Mammal, Animal, Object, Kernel, BasicObject]
因為返回的陣列中存在 Animal,所以 whale.is a?(Animal) 也是 true。
在 Ruby 中使用 kind_of? 檢查物件的型別
is_a? 是 kind of? 的別名。
dophin = Mammal.new
dophin.kind_of?(Animal)
# => true
dophin.kind_of?(Mammal)
# => true
在 Ruby 中使用 instance_of? 檢查物件的型別
與 is a? 不同,instance of? 不檢查物件的祖先。如果一個物件是給定類的一個例項,它返回 true;否則,它返回 false。
cat = Mammal.new
cat.instance_of?(Mammal)
# => true
cat.instance_of?(Animal)
# => false
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe