为什么"super"是关键字而不是Ruby中的方法? [英] Why is 'super' a keyword rather than a method in Ruby?
问题描述
In Ruby, super
is a keyword rather than a method.
为什么要这样设计?
Ruby的设计趋向于实现尽可能多的方法.关键字通常保留给具有自己语法规则的语言功能.但是,super
的外观和行为类似于方法调用.
Ruby's design tends toward implementing as much as possible as methods; keywords are usually reserved for language features that have their own grammar rules. super
, however, looks and acts like a method call.
(我知道在纯Ruby中实现super
会很麻烦,因为它必须从caller
或内核的方法未在纯Ruby中实现.)
(I know it would be cumbersome to implement super
in pure Ruby, since it would have to parse the method name out of caller
, or use a trace_func. This alone wouldn't prevent it from being a method, because plenty of Kernel's methods are not implemented in pure Ruby.)
推荐答案
它的行为略有不同,因为如果您不传递参数,则会传递所有当前参数(如果存在则为block). .我不确定该方法将如何工作.
It behaves a little differently, in that if you don't pass arguments, all of the current arguments (and block, if present) are passed along... I'm not sure how that would work as a method.
举一个比较人为的例子:
To give a rather contrived example:
class A
def example(a, b, c)
yield whatever(a, b) + c
end
end
class B < A
def example(a, b, c)
super * 2
end
end
我不需要处理产量,也不需要将参数传递给super
.在您特别想传递不同参数的情况下,它的行为更像是方法调用.如果您根本不想传递任何参数,则必须传递空括号(super()
).
I did not need to handle the yield, or pass the arguments to super
. In the cases where you specifically want to pass different arguments, then it behaves more like a method call. If you want to pass no arguments at all, you must pass empty parentheses (super()
).
它根本没有与方法调用完全相同的行为.
It simply doesn't have quite the same behaviour as a method call.
这篇关于为什么"super"是关键字而不是Ruby中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!