在《鲁宾达方案语言》(第270页)中,我混淆了<代码>instance_eval的原因。 样本代码最后一行的计算方法 定义了一种类别方法 称String.empty
。
Don t You use class_eval
to establish a category methods and 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")