首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

class_eval跟module_eval方法

2012-09-03 
class_eval和module_eval方法??http://blackanger.blog.51cto.com/140924/84057/??Thing.module_eval(a)pu

class_eval和module_eval方法

?

?

http://blackanger.blog.51cto.com/140924/84057/

?

?


Thing.module_eval(a)
puts Thing.new.hello()
=>??Hello there!


我真没想到Matz还到ruby-forum里去混, 姑且认为是Matz本人吧,他给出的答案是:

用#{y}是在compile time 的时候已经把y的值传给了class_eval.
在运行时, puts “#{y}” 已经变成了 puts “another hi”
而变量y,则因为作用域的不同,外部定义的局部变量y是class_eval无法收到的。

这有个有意思的例子更加说明了这一点:

class T
????def first
????????"hello"
????end
????def second
????????"chunky bacon"
????end
end

y = "first"

T.class_eval <<-END
????def hello
????????puts #{y}
????end
END

T.new.hello
=>prints "hello"

关键点是, #{y}是作为string的一部分传给了class_eval.? 此时已经是puts first了。 而不是在call hello方法的时候去找y

本文出自 “{ :Alex Space => &..” 博客,请务必保留此出处http://blackanger.blog.51cto.com/140924/84057

热点排行