IntelliData IntelliData - 1 year ago 49
Ruby Question

Why does @Array.clear not work

I'm doing the about_dice_project.rb in ruby koans. I defined the class DiceSet with the roll method as follows:

class DiceSet
attr_reader :values

def initialize
@values = []
@old_values = []

def roll(num_dice)
@old_values = @values

while @values == @old_values do
@values = []

(1..num_dice).each do
rnd = 1 + rand(6)
@values << rnd

I replaced

@values = []



and it doesn't work; the ruby terminal just freezes. Can anyone tell me what I'm doing wrong?

Thank You!

Answer Source

When running @old_values = @values, both variables point to the exactly same object. Now, when you assign a new array to @values as in @values = [], @values now is a different array object.

However when running @values.clear, you are changing the existing array, i.e. the same @old_values still points to. In this case, when adding new entries to @values, you are adding them to @old_values too (as they both point to the same object).

You should read a bit more about how Ruby handles variables and objects. This is part of the first lessons of about all Ruby tutorials.