Tuesday, 17 September 2013

Why are my instance variables not existing across methods of the same class in ruby?

Why are my instance variables not existing across methods of the same
class in ruby?

I am doing the ruby koans and I am on the DiceSet project. I've made the
DiceSet class but my instance variables don't seem to persist with the
instance like I thought they would. My code is
class DiceSet
attr_reader :values
@values = []
puts @values.class
def roll(number_of_rolls)
(1..number_of_rolls).each do |roll|
puts @values.class
@values << (1..6).to_a.sample
end
return @values
end
end
The koan then uses my DiceSet class with
dice = DiceSet.new
dice.roll(5)
puts dice.values.class
assert dice.values.is?(Array)
I put the puts commands in there to follow whats happening with the
@values instance variable and only the first puts @values.class says its
an Array class. All the others are returning NilClass. Am I using instance
variables incorrectly or is there something else I am missing? Do instance
variables get deallocated after a method call?

No comments:

Post a Comment