Ruby attr_accessor有多个类

时间:2013-11-30 15:51:27

标签: ruby attr-accessor

很抱歉新手问题,但如何向多个类传递/访问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}"

1 个答案:

答案 0 :(得分: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