(問題已發佈在Ruby Forum,但沒有在那裏引起任何答案)。動態添加實例方法無法訪問類變量
這是我的代碼:
class MC
def initialize
@x = 5
@@y = 6
end
def f
puts @x
puts @@y
end
end
m = MC.new
m.f
m.f
產生預期的輸出沒有錯誤:
5
6
但這:
def m.g
puts @x
puts @@y
end
m.g
生產:
5
warning: class variable access from toplevel
NameError: uninitialized class variable @@y in Object
爲什麼我可以從f
訪問@@y
,但不能從g
訪問?
在提示中提到toplevel
和Object
,錯誤信息令我費解。
@x
打印爲5
,所以其環境爲MC
。這排除了m.g
的定義中的@x
和@@y
參考頂級環境(Object
)而不是MC
的可能性。
爲什麼我收到錯誤信息?
這是之前問過的:http://stackoverflow.com/q/24510948/477037 – Stefan
@Stefan:是的。不幸的是,這裏也沒有很好的解釋。 –