在这个来自Ruby Programming Language(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 …Run Code Online (Sandbox Code Playgroud)