在這個例子中,從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")