【发布时间】:2009-09-07 07:43:38
【问题描述】:
在Ruby 编程语言 (p.270) 的这个例子中,我很困惑为什么示例代码最后一行的instance_eval 方法定义了一个类方法 称为String.empty。
你不是用class_eval定义类方法,用instance_eval定义实例方法吗?
o.instance_eval("@x") # Return the value of o's instance variable @x
# Define an instance method len of String to return string length
String.class_eval("def len; size; end")
# Here's another way to do that
# The quoted code behaves just as if it was inside "class String" and "end"
String.class_eval("alias len size")
# Use instance_eval to define class method String.empty
# Note that quotes within quotes get a little tricky...
String.instance_eval("def empty; ''; end")
【问题讨论】:
标签: ruby reflection