【Ruby】怎样判断一个类是否有某个方法,一个实例是否有某个属性?

当调用不存在的方法或属性时,Ruby将抛出错误。因此防御性的做法是提前检测方法或属性是否存在。

使用 method_defined? 检测类中是否存在某个方法:

String.method_defined?(:to_i)
=> true

# I see that there is a to_i method, so I'm going to run it
"1".to_i
=> 1

使用 respond_to? 检测实例中是否存在某个属性:

"string".respond_to?(:to_a)
=> false

版权声明:本文为henryhu712原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。