With the following code:
class ObjA
def func
puts "ObjA"
end
end
module Mod
def func
puts "Mod"
end
end
class ObjB < ObjA
include Mod
def func
puts "super called"
super
puts "super.func called"
super.func
end
end
Running ObjB.new.func results in:
ruby-1.9.2-p180 :002 > ObjB.new.func
super called
Mod
super.func called
Mod
NoMethodError: undefined method `func' for nil:NilClass
from test.rb:19:in `func'
from (irb):2
I understand what super does - it calls the current method on the superclass. include Mod makes Mod the next superclass so Mod开发者_运维知识库#func is called.
However, what is super.func doing? I thought it would be equivalent to super, but while it does print out the same output, it also throws a NoMethodError.
I assume super.func would do the same thing as any form of method chaining. It calls super, and then calls func on the result returned by super.
The super part would call Mod#func, which prints out "Mod", then calls func on the return value of Mod#func, ie nil (that's because puts returns nil). As nil doesn't have a func method, it says
NoMethodError: undefined method `func' for nil:NilClass
from test.rb:19:in `func'
from (irb):2
加载中,请稍侯......
精彩评论