我正在阅读《Pickaxe Book》,作者提供了以下示例作为一种在不使用实例变量的情况下给模块/混入状态的技巧:
...该模块可以使用一个模块级哈希表,通过当前对象ID进行索引,以存储特定于实例的数据...
module Test
State = {}
def state=(value)
State[object_id] = value
end
def state
State[object_id]
end
end
class Client
include Test
end
c1 = Client.new
c2 = Client.new
c1.state = 'cat'
c2.state = 'dog'
c1.state # => "cat"
c2.state # => "dog"
我不太清楚这个是如何工作的。特别是object_id
。object_id
方法是如何以这种方式访问Client
实例的?我尝试使用length
看是否可以根据它进行索引,但是我得到了以下结果:
NameError: undefined local variable or method `length' for #<Client:0x00000000ecc570>
我希望能够确保自己理解这里所发生的原理。
<pre>
标签来展示代码,而是使用缩进 4 个空格的方式。因为<pre>
标签不能正确地进行 HTML 转义,所以类似标签的内容(例如<Client:0x00000000ecc570>
)将无法显示。 - Amadan