在下面来自ruby docs的代码中,为什么orig_exit没有在无限递归中调用自己呢?
module Mod
alias_method :orig_exit, :exit
def exit(code=0)
puts "Exiting with code #{code}"
orig_exit(code)
end
end
include Mod
exit(99)发布于 2012-09-06 12:38:32
为什么orig_exit不在无限递归中调用自己呢?
因为这里没有递归。
首先,从最后一行(exit(99))调用exit,然后调用orig_exit,这是一个不同的函数。除非orig_exit显式调用exit (没有理由相信它会这样做),否则就不可能出现递归。当orig_exit返回时,它的返回值也从exit返回。
alias_method已将名为exit的方法重命名为orig_exit,然后定义了一个名为exit的全新函数。
https://stackoverflow.com/questions/12293048
复制相似问题