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}"

person Carmen Puccio    schedule 30.11.2013    source источник
comment
Какой у Вас вопрос ?   -  person Arup Rakshit    schedule 30.11.2013
comment
Хорошая программа. Что за вопрос?   -  person joews    schedule 30.11.2013


Ответы (1)


Экземпляр класса 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
person user2422869    schedule 30.11.2013