ruby - 为什么带有 initialize() 的 respond_to 返回 false?

标签 ruby class

为什么我在执行 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/

相关文章:

python - 为什么一个类需要 __iter__() 来返回一个迭代器?

c++ - 类具有std::unordered_set的相同类的指针

ruby-on-rails - 查找 Rails 应用程序中的内存泄漏

ruby-on-rails - 在不输入源代码的情况下在rails中设置测试环境变量

Ruby:空间可能出现的 Ubuntu Gedit 问题

class - UML:《原始语》的含义

java - 在不扩展它的类中使用抽象类方法

ruby - 是否定义了 Ruby 散列的每个值的顺序?

ruby - RVM - 我需要 Ruby 1.8.7 才能安装 Ruby 1.9 吗?

javascript - 确认使用工厂是创建通用多用途点击计数监听器的最佳(唯一?)方法