ruby - 元编程:method_missing 和 __send__

标签 ruby metaprogramming method-missing

我发现 Ruby 有一个奇怪的地方。当内核定义相同的方法时,使用 method_missing/respond_to_missing? 动态处理通过 __send__ 发起的方法调用会失败:

class Testerize

  def method_missing(method, *args, &block)
    if method == :system
      puts 'yay'
    else
      super
    end
  end

  def respond_to_missing?(method, internal)
    return true if method == :system
  end

end

t = Testerize.new
puts t.respond_to?(:system)
# Prints true
t.system
# Prints 'yay'
t.__send__(:system)
# Exception: wrong number of arguments (ArgumentError)

Kernel.system 以某种方式融入其中。有谁知道这是怎么回事?我本希望将 :system “消息”发布到 Testerize 实例,点击 method_missing,瞧。为什么我的 method_missing 在使用 __send__ 时没有被调用,而它是直接调用的?

我正在使用 Ruby 1.9.3(如果相关的话)。

最佳答案

with '__send__' or 'send' we can even call private methods of the object.

在您的脚本中执行以下操作:

t.private_methods.grep /system/

您将看到system方法,同时使用

t.methods.grep /system/

您将看到一个空数组。

__send__ 尝试调用继承链中从 Kernel 继承的私有(private)方法,因此不要使用 __send__,而是使用 Ruby 的 public_send 方法。

关于ruby - 元编程:method_missing 和 __send__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602380/

相关文章:

ruby-on-rails - 如何在 Rails 中使用关联搜索 group_by

c++11 - 如何检查一个类是否有运算符[]?

r - R 中特定列的总和 NA

Ruby "method_missing"创建方法后运行

ruby - method_missing

ruby 测试 : Testing for the Absence of a Method

ruby-on-rails - Rails STI 类自动初始化

ruby-on-rails - 如何在 Rails 模型中创建多个类和实例方法

ruby - 我怎样才能 "replace"通过 ruby​​ include 函数包含的模块

Ruby 参数化 if ... then block