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