新手问题 请问模块级散列表的含义啊

p0p3 · 2013年07月08日 · 最后由 iBachue 回复于 2013年07月08日 · 2215 次阅读

在 programming ruby 书中介绍,为了保证模块中的实例变量具有唯一的名字,可以使用模块一级的散列表,以当前对象的 ID 作为索引,来保存实例的数据

module Test
State = {}
def state=(value)
State[object_id] = value
end

def state
State[object_id]
end
end

请问下模块一级的散列表,开头为大写,还有人具体讲解下模块一级的散列表的含义啊

简单试了下 感觉在 Module 中用大写字母的 Constant 就是为了想全局变量一样的共享吧。。

 0  ~/tmp/test-project  irb
1.9.3p429 :001 > module Test
1.9.3p429 :002?>
1.9.3p429 :003 >     State = {}
1.9.3p429 :004?>
1.9.3p429 :005 >     def state=(value)
1.9.3p429 :006?>
1.9.3p429 :007 >       State[object_id] = value
1.9.3p429 :008?>
1.9.3p429 :009 >       end
1.9.3p429 :010?>
1.9.3p429 :011 >     def state
1.9.3p429 :012?>
1.9.3p429 :013 >       State[object_id]
1.9.3p429 :014?>
1.9.3p429 :015 >       end
1.9.3p429 :016?>
1.9.3p429 :017 >     end
 => nil
1.9.3p429 :018 > class A; include Test; end
 => A
1.9.3p429 :019 > A::State
 => {}
1.9.3p429 :020 > a = A.new
 => #<A:0x007f929b016848>
1.9.3p429 :021 > a.state = 1
 => 1
1.9.3p429 :022 > a.state
 => 1
1.9.3p429 :023 > A::State
 => {70133821256740=>1}
1.9.3p429 :024 > Test::State
 => {70133821256740=>1}
1.9.3p429 :025 > class B; include Test; end
 => B
1.9.3p429 :026 > b = B.new
 => #<B:0x007f92990f6008>
1.9.3p429 :027 > b.state
 => nil
1.9.3p429 :028 > b.state = 2
 => 2
1.9.3p429 :029 > b.state
 => 2
1.9.3p429 :030 > b2 = B.new
 => #<B:0x007f9299061d40>
1.9.3p429 :031 > b2.state
 => nil
1.9.3p429 :032 > b2.state = 3
 => 3
1.9.3p429 :033 > b2.state
 => 3
1.9.3p429 :034 > Test::State
 => {70133821256740=>1, 70133804937220=>2, 70133804633760=>3}
需要 登录 后方可回复, 如果你还没有账号请 注册新账号