在这个例子中,从Ruby编程语言(第270页),我很困惑,为什么上示例代码的最后一行instance_eval
方法定义了类方法称为String.empty
。需要与反思例如帮助从“Ruby编程语言”
当您要定义实例方法时,是否使用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")