如何在 Ruby 中重新定义 Fixnum 的 + (plus) 方法并保持原始 + 功能? [英] How can I redefine Fixnum's + (plus) method in Ruby and keep original + functionality?
本文介绍了如何在 Ruby 中重新定义 Fixnum 的 + (plus) 方法并保持原始 + 功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这在 1.9.2 Ruby 中引发了 SystemStackError(但在 Rubinius 中有效):
This throws me a SystemStackError in 1.9.2 Ruby (but works in Rubinius):
class Fixnum
def +(other)
self + other * 2
end
end
但是+
没有super
(基于其他错误).
but there is no super
for +
(based on other errors).
如何访问原始的 +
功能?
How can I access the original +
functionality?
推荐答案
使用 alias_method
.将Fixnum
的+
别名为别的东西,然后在新的+
中引用:
Use alias_method
. Alias Fixnum
's +
to something else, then refer to it in the new +
:
class Fixnum
alias_method :old_add, :+
def +(other)
self.old_add(other) * 2
end
end
这篇关于如何在 Ruby 中重新定义 Fixnum 的 + (plus) 方法并保持原始 + 功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文