super.是什么意思?在红宝石中做什么?
使用以下代码:
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
运行 ObjB.new.func
结果:
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
我理解 super
的作用 - 它调用超类的当前方法。 include Mod
使 Mod 成为下一个超类,因此调用 Mod#func
。
然而,super.func
正在做什么?我认为它相当于 super
,但虽然它确实打印出相同的输出,但它也会抛出 NoMethodError
。
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
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设 super.func 会做与任何形式的方法链接相同的事情。它调用
super
,然后对super
返回的结果调用func
。super
部分将调用Mod#func
,打印出“Mod”,然后在Mod# 的返回值上调用
,即 nil(这是因为func
funcputs
返回 nil)。由于 nil 没有func
方法,所以它说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