確定 Ruby 中的物件型別
Stewart Nguyen
2023年1月30日
Ruby
Ruby Object
Ruby Methods
在本文中,我們將學習在 Ruby 程式語言中檢查物件的型別。
在 Ruby 中使用 #class 確定例項的類名
此方法返回當前例項的類名。例如:
'string'.class
=> String
[].class
=> Array
{}.class
=> Hash
String.class
=> Class
Ruby 是一種物件導向的程式語言,其中的一切都是物件。Classes 也是 Class 類的物件。這就是 String.class 返回 Class 的原因。
在 Ruby 中使用 #class 定義類
class Human; end
alice = Human.new
alice.class
輸出:
Human
在 Ruby 中使用 #is_a? 確定例項的類名
如果給定的物件是 class 的例項,則返回 true;否則,它返回 false。
'string'.is_a?(String)
=> true
[].is_a?(Hash)
=> false
如果物件是任何子類的例項,#is_a 也會返回 true。
考慮以下場景:
class Ape; end
class Sapiens < Ape; end
alice = Sapiens.new
alice.is_a?(Sapiens)
輸出:
true
alice 是 Sapiens,但是 alice.is_a?(Ape) 呢?
alice.is_a?(Ape)
輸出:
true
令人驚訝的是,alice 也是 Ape,因為 Sapiens 的祖先陣列中包含 Ape。
Sapiens.ancestors
=> [Sapiens, Ape, Object, Kernel, BasicObject]
從輸出中可以看出,Ape 是 Sapiens 的祖先,所以 alice 是 Ape。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe