Alex学Ruby[ class_eval(module_eval)现形记]

class_eval和module_eval方法一样, 都是为一个class增加method的。 可以接string和block为参数。 此方法是Ruby的动态特性之一。

class Thing
end
a = %q{def hello() "Hello there!" end}

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


例子:
class Wes
end

Wes.class_eval <<-END
     def hello
         puts "#{y}"
         puts y
     end
END
Wes.new.hello
=> another hi
NameError: undefined local variable or method `y' for #<Wes:0


那么:what's the diff between puts y and puts "#{y}" in class_eval  ?

我真没想到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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值