新手问题 alias 后的影响

ane · 2014年01月04日 · 最后由 sallon88 回复于 2014年01月07日 · 2712 次阅读

我先上代码

def hello
   puts "hello world"
end
alias ori_hello hello

def hello
  puts "a new hello"
  ori_hello
  puts "this is a new hello"
end 

问题: 1:旧的 hello 是不是已经不存在了?如果存在如何调用(除了用 ori_hello) 2: 新的 hello 算是给旧的 hello 方法新增功能吗?与元编程有何不同?

  1. orig_hello只是对 hello 方法的拷贝,hello方法并没有消失,只是在重新定义hello方法之后,hello的行为变了。(后者是我的猜测)
  2. 新的 hello 方法就是扩展了旧的 hello 方法的功能。但至于猴子补丁跟元编程的区别,就真的是学得还不够,没法表达清楚。

坐等大牛们正解!

以下内容纯属臆测

首先,你可以想像有一张表在维护着 方法名方法体 的映射。

方法名是方法体的名字 (废话), 比如 hello, ori_hello 就是方法名。 方法体是计算机内部对象,我们估且称呼不同的方法体为方法体1,方法体2吧

方法名 belongs_to 方法体 方法体 has_many 方法名

就你以上的例子: def hello后,映射表是这样的 hello --> 方法体 1

alias ori_hello hello后,映射表是这样的 hello --> 方法体1 ori_hello --> 方法体1

def hello后 映射表是这样子的 hello --> 方法体2 ori_hello --> 方法体1

所以, 问题 1.1: 旧的 hello(即方法体1) 依旧存在,只不过现在它只有一个方法名叫 ori_hello。 问题 1.2: 实际上我们是可以在代码中获取到方法体的,所以不用 ori_hello,也是可以调用旧 hello 的

def hello
  puts 'hello world'
end
method_body = method :hello

def hello
  puts 'hello china'
end
hello // ==> hello china
method_body.call //==> hello world

问题 2.1: 新的 hello(即方法体2) 跟旧的 hello(即方法体1)没有一毛钱关系。只不过是 凑巧 在方法体2中调用了方法体1而已。 问题2.2: There is no such thing as metaprogramming. It's just programming all the way through.

一个 cp,一个 mv.

#3 楼 @sallon88 数据表这种思考方式,很像 java 虚拟机的工作方式啊

#3 楼 @sallon88 能详细解释一下你的“method_body = method :hello”这行吗?因为我不知道这个 method:是什么意思,它属于那个类库,是那个类之类的信息,或者给我一个 google 的关键字,让我进一步了解一下

@u1378130755 method 是个方法

需要 登录 后方可回复, 如果你还没有账号请 注册新账号