为什么我在执行 C.respond_to?(:initialize)
时得到 false
class C
def initialize;end
def meth;end
end
C.respond_to?(:initialize) #=> false
C.new.respond_to?(:meth) #=> true as expected
另一种变化
class C
def initialize;end
def meth
pmeth
end
private
def pmeth
respond_to?(:initialize)
end
end
最佳答案
这是因为#initialize
不是公共(public)方法。如果您想使用 #respond_to?
检查私有(private)的、 protected 方法, 将第二个参数设置为 true
。
文档清楚的说
Returns true if obj responds to the given method. Private and protected methods are included in the search only if the optional second parameter evaluates to true.
见下文:
class C
def initialize;end
def meth;end
end
C.respond_to?(:initialize,true)
# => true
C.new.respond_to?(:initialize)
# => false
C.new.respond_to?(:initialize,true)
# => true
C.private_methods(false).include?(:initialize) # => true
C.new.private_methods(false).include?(:initialize) # => true
关于ruby - 为什么带有 initialize() 的 respond_to 返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18489820/