Question

Sorry for the newbie question but how do I pass/access attar_accessor to and from multiple classes? in my example below the Foo class never is able to see the updated values from the Level class.

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}"
Was it helpful?

Solution

Instance of Level class you declaring in Foo's constructor and @testb are two different objects.

You might want to edit your Foo class this way:

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

And then do your tests:

level = Level.new() # BTW: no need of instance variables here.
foo = Foo.new(level) # good job. Your foo has "captured" the level.
# et cetera
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top