与超级混淆
覆盖 to_xml。
这些代码有什么区别。有人可以用适当的例子解释一下吗?
1.
def to_xml(options = {})
options.merge!(:methods => [ :murm_case_name, :murm_type_name ])
super
end
2.
def to_xml(options = {})
super
options.merge!(:methods => [ :murm_case_name, :murm_type_name ])
end
Override to_xml.
What are the difference between these codes. Can someone explain it with proper example ?
1.
def to_xml(options = {})
options.merge!(:methods => [ :murm_case_name, :murm_type_name ])
super
end
2.
def to_xml(options = {})
super
options.merge!(:methods => [ :murm_case_name, :murm_type_name ])
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
tl;dr:
super
以意想不到的方式运行,变量很重要,而不仅仅是对象。当调用
super
时,不会使用传入的对象来调用它。而是使用调用时名为
options
的变量来调用。例如,使用以下代码:生成输出
您可以看到,使用
SecondChild
时,使用变量options
调用 super 方法,该变量引用Fixnum< /code> 的值
42
,而不是最初由options
引用的对象。通过使用
options.merge!
,您可以修改传递给您的哈希对象,这意味着变量original_child_options
引用的对象现在已被修改,如下所示可以在Original child options after method called: {:methods=>[:murm_case_name, :murm_type_name]}
行中看到。(注意:我在 SecondChild 中将
options
更改为 42,而不是调用Hash#merge
,因为我想表明这不仅仅是对对象产生副作用的情况)tl;dr:
super
behaves in unexpected ways, and variables matter, not just objects.When
super
is called, it's not called with the object that was passed in.It's called with the variable that is called
options
at the time of the call. For example, with the following code:Which produces the output
You can see that with
SecondChild
the super method is called with the variableoptions
which refers to aFixnum
of value42
, not with the object that was originally referred to byoptions
.With using
options.merge!
, you'd modify the hash object that was passed to you, which means that the object referred to by the variableoriginal_child_options
is now modified, as can be seen in theOriginal child options after method called: {:methods=>[:murm_case_name, :murm_type_name]}
line.(Note: I changed
options
to 42 in SecondChild, rather than callHash#merge
, because I wanted to show it wasn't merely a case of side effects on an object)第一个返回 super 调用的结果。所以就像你从来没有对你的情况做某事一样。
第二次在更改之前调用 super 并在更改之后调用 super 。
我想你真的想要:
the first return the result of super call. So it's like you never to something in your case.
The second call super before your change and change options after.
I suppose you really want :