2013-11-30 2 views
0

Извините за вопрос о новичке, но как передать/получить доступ attar_accessor к нескольким классам? в моем примере ниже класс Foo никогда не может видеть обновленные значения из класса Level.Ruby attr_accessor несколько классов

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

Что ваш вопрос? –

+0

Хорошая программа. Что за вопрос? – joews

ответ

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 
Смежные вопросы