gpt4 book ai didi

ruby - 与状态混合

转载 作者:数据小太阳 更新时间:2023-10-29 07:52:11 25 4
gpt4 key购买 nike

我正在研究“Pickaxe Book”,作者给出了以下示例作为一种在不使用实例变量的情况下提供模块/混合状态的技术:

...the module could use a module-level hash, indexed by the current object ID, to store instance-specific data...

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_idobject_id 方法如何能够以这种方式访问​​ Client 实例?我尝试使用 length 来查看它是否会根据该索引进行索引,但我得到了:

NameError: undefined local variable or method `length' for #<Client:0x00000000ecc570>

我想确保我理解这里发生的事情的原则。

最佳答案

How is the object_id method able to access the Client instance in this manner?

  1. state=() 方法在包含时从 Test 模块继承。包含模块创建一个匿名类,该类插入继承链中包含类的正上方。

  2. 这一行:

    c1.state = 'cat'

    相当于:

    c1.state=('cat')

    而当c1调用state=()时,state=()方法内部的self会是等于 c1。在 def 中,self 等于调用该方法的对象。

  3. 当您调用没有接收者的方法时,self 就是隐式接收者。在 state=() 内:

    def state=(value)
    State[object_id] = value
    end

    调用 object_id() 方法时没有接收者,因此 self 成为接收者。结果,该行:

    State[object_id] = value

    相当于:

    State[self.object_id] = value

    相当于:

    State[c1.object_id] = value

关于ruby - 与状态混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33601263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com