alias_method递归

use*_*873 1 ruby alias

在以下来自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)
Run Code Online (Sandbox Code Playgroud)

mea*_*gar 5

为什么orig_exit最终不会在无限递归中调用自身?

因为这里没有递归.

首先,exit从最后一行exit(99)调用orig_exit,然后调用,这是一个不同的函数.除非orig_exit显式调用exit(没有理由相信它),否则不可能进行递归.当orig_exit返回时,它的返回值从返回exit为好.

alias_method已经更名,该方法命名exitorig_exit,然后一个名为全新的功能exit定义.