从扩展模块调用基类方法的奇怪输出

时间:2012-07-31 09:20:25

标签: ruby module mixins

我想要实现的是下面的内容,即从扩展模块方法调用基类方法:

class BaseClass
  def behavior
    puts 'base class behavior'
  end
end

module ChildModule
  def behavior
   super.behavior
   puts 'child module behavior'
  end
end

o = BaseClass.new
o.extend ChildModule
o.behavior

并输出如下(使用ruby 1.9.2p290(2011-07-09修订版32553)[x86_64-linux])

base class behavior
t.rb:9:in `behavior': undefined method `behavior' for nil:NilClass (NoMethodError)
       from t.rb:16:in `<main>'

我的猜测是我无法使用super,因为模块中不存在super。但它打印出来自super方法的那条线,是不是很奇怪?

我如何实现上述目标?

@davidrac的回答是有效的,但是更加好奇,想知道,我怎样才能得到基类实例的句柄?比方说,我将以下方法添加到BaseClass

def behavior2
  puts 'base class behavior2'
end

并在ChildModule中覆盖它。现在从ChildModule行为我可以调用BaseModule的behavior2吗?

1 个答案:

答案 0 :(得分:1)

我认为正确的语法是:

module ChildModule
  def behavior
   super
   puts 'child module behavior'
  end
end
相关问题