0

对不起新手问题,但我如何传递/访问 attar_accessor 到多个类?在下面的示例中, Foo 类永远无法从 Level 类中看到更新的值。

class Level
  attr_accessor :level, :speed
end

class Foo
  attr_reader :a, :b
  def initialize
    @x = Level.new()
    @a = @x.level
    @b = @x.speed
  end

  def reload
    @a = @x.level
    @b = @x.speed
  end
end

@testa = Foo.new()
@testb = Level.new()

@testb.level = 5
@testb.speed = 55

puts "Value for attr_accessor is:"
puts "#{@testb.level}"
puts "#{@testb.speed}"

puts "#{@testa.a}"
puts "#{@testa.b}"

@testa.reload

puts "#{@testa.a}"
puts "#{@testa.b}"
4

1 回答 1

2

您在构造函数中Level声明的类的实例是两个不同的对象。Foo's@testb

您可能希望以Foo这种方式编辑您的课程:

class Foo 
  def initialize(level)
    @x = level  # very strange name for such a thing.
    @a = @x.level
    @b = @x.speed
  end
  # rest of the class body is the same as yours
  # so it is omitted
end

然后做你的测试:

level = Level.new() # BTW: no need of instance variables here.
foo = Foo.new(level) # good job. Your foo has "captured" the level.
# et cetera
于 2013-11-30T16:16:04.113 回答