English 中文(简体)
B. 需要帮助思考“鲁比方案拟订语言”的例子
原标题:Need help with reflection example from "The Ruby Programming Language"
  • 时间:2009-09-07 07:43:38
  •  标签:

《鲁宾达方案语言》(第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")
最佳回答
问题回答




相关问题
热门标签