通过其中一个参数引用对象

时间:2011-12-20 05:13:50

标签: ruby

假设您的类具有类Bar1,Bar2,Bar3的实例变量。 Bar类定义是任意的,为了举例,它们的名称相似。

class Foo
  attr_reader :test_value

  def initialize
    @test_value = "awesome"
    @bar1 = Bar1.new
    @bar2 = Bar2.new
    @bar3 = Bar3.new
  end
end

其中Bar1,Bar2,Bar3定义为

class Bar1
  def initialize
    @value = owner.test_value # 'owner' would refer the Foo instance that contains this Bar1
  end
end

class Bar2
  def initialize
    @value = owner.test_value
  end
end

class Bar3
  def initialize
    @value = owner.test_value
  end
end

我只是为了演示而编造了所有者的价值,这样的事情是否可能?这似乎是一种延伸,并且可能只需重新构建我需要此功能的代码就可以解决,但我想看看在完全抛弃它之前是否可能。

谢谢!

2 个答案:

答案 0 :(得分:1)

class Foo
  attr_reader :test_value

  def initialize
    @test_value = "awesome"
    @bar1 = Bar1.new(self)
    @bar2 = Bar2.new(self)
    @bar3 = Bar3.new(self)
  end
end

class Bar1
  def initialize owner
    @value = owner.test_value
  end
end

class Bar2
  def initialize owner
    @value = owner.test_value
  end
end

class Bar3
  def initialize owner
    @value = owner.test_value
  end
end

答案 1 :(得分:0)

对象无法分辨它的“所有者”是什么,因为它可以一次分配给一千个不同的变量。唯一的近似是在创建对象时显式设置实例变量,例如:

def Foo
  attr_reader :test_value, :bar1

  def initialize
    @test_value = 'awesome'

    @bar1 = Bar1.new
    @bar1.owner = self  # you could also make Bar1#new take an argument which
  end                   # would be assigned to @owner
end

def Bar1
  attr_accessor :owner

  def initialize
    # ...
  end

  def value
    owner.test_value
  end
end

f = Foo.new
f.bar1.value # => 'awesome'