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 callssuper
, and then callsfunc
on the result returned bysuper
.The
super
part would callMod#func
, which prints out "Mod", then callsfunc
on the return value ofMod#func
, ie nil (that's becauseputs
returns nil). As nil doesn't have afunc
method, it says