`method_missing`和`puts`发生了什么?

时间:2016-01-24 05:41:50

标签: ruby

我打印了一组实现ancova()方法的对象。以下示例演示了这一点:

method_missing

输出

class Foo
  def method_missing(m, *args, &block)
    puts "missing method in #{self.class} #{m}"
    super
  end
end

bar = [Foo.new, Foo.new, Foo.new]

bar.each { |i| puts "#{i}" }
puts "====================="
bar.each { |i| puts i }
puts "====================="
Foo.new.to_ary 
  1. 为什么要调用#<Foo:0x00000000d62ba8> #<Foo:0x00000000d62b80> #<Foo:0x00000000d62b58> ===================== missing method in Foo to_ary #<Foo:0x00000000d62ba8> missing method in Foo to_ary #<Foo:0x00000000d62b80> missing method in Foo to_ary #<Foo:0x00000000d62b58> ===================== missing method in Foo to_ary ./missing_test.rb:6:in `method_missing': undefined method `to_ary' for #<Foo:0x00000000d61e60> (NoMethodError) from ./missing_test.rb:16:in `<main>' ? (我认为它与to_ary试图挖掘并递归提供一些信息的方式有关。)
  2. 为什么对puts的调用(由to_ary生成)不会产生puts错误? missing_method(或Foo)不支持此功能。我的所有Object方法都会打印方法名称,然后调用method_missing,因此如果super显示为缺失,则对to_ary的调用应抛出super例外,对吧?

0 个答案:

没有答案