做一个元编程练习时被难倒了,贴出来,看看各位有啥好主意 http://ruby-metaprogramming.rubylearning.com/html/Exercise_1.html
class A
def initialize
@a = 11
@@a = 22
a = 33
end
@a = 1
@@a = 2
a = 3
end
最后 end 前的三行赋值代码我是不是可以理解成跟 java 的 static 块方法一样的功能?
#1 楼 @themorecolor #3 楼 @chenge #5 楼 @tumayun #7 楼 @ywjno
网上找到一个解决方案 class_local_a = class A def initialize @a = 11 @@a = 22 a = 33 end @a = 1 @@a = 2 a = 3 end
p A.instance_variable_get(:@a) #ok
p A.class_variable_get(:@@a) if RUBY_VERSION > '1.9' class A; p @@a end if RUBY_VERSION < '1.9'
p class_local_a
p A.new.instance_variable_get(:@a)
p A.class_variable_get(:@@a) if RUBY_VERSION > '1.9' class A; p @@a end if RUBY_VERSION < '1.9'
p A.new.method(:initialize).call