ruby 中的每个表达式都有返回值,默认是最后一条语句的返回值,不知到你注意到了没有?
1.
a1 = class A
end
=> nil # return nil
2.
a2 = class A
self
end
=> A # return a
3.
class A
@a = 10
class << self
@a = 20
end
end
=> 20
A.instance_variable_get :@a
=> 10 #为什么是10,二不是20呢? 怎么样才能取到20?
先看看返回值有什么不同:
4.
a4 = class A
@a = 10
class << self
@a = 20
self
end
end
=> #<Class:A> #这是什么东西,为什么和例2不一样呢?
a2.class
=> Class
a4.class
=> Class
a2.singleton_class
=> #<Class:A>
看到这里,应该知道怎么取到@a = 20 了吧
a4.instance_variable_get :@a
=> 20
or
A.singleton_class.instance_variable_get :@a
=> 20
5.
a5 = class << A; self end
=> #<Class:A>
6.
a6 = def A.f
self
end
A.f
=> A
7.
class A
class << self
def f
"f"
end
class << self
def f
"ff"
end
end
end
end
A.f
=> "f“
A.singleton_class.f
=> "ff"