Ruby Koans - Array population method affects how it returns -
i've been working on ruby koans , i've gotten part don't understand well. specifically, it's about_dice_project, ask define class pass several pre-set tests. originally, class looked like
class diceset attr_accessor :values def initialize @values = [] end def roll(num) num.times { |i| @values[i] = rand(1..6) } return @values end end
but failed test below
dice = diceset.new dice.roll(5) first_time = dice.values dice.roll(5) second_time = dice.values assert_not_equal first_time, second_time, "two rolls should not equal"
and realized after testing both first_time , second_time have same object_id. looked on stackoverflow , found this answer, doesn't answer question directly, did find major difference in our code; namely, instead of using "num.times" way of rolling dice, goes instead with
@values = array.new(num) { rand(1..6) }
and pass above test.
after finding this, trying figure out why original code didn't work, , thought maybe ruby passing reference, , that's why when dice-rolling-method created new array instead of modifying existing array, new object id created. found this question, says ruby pass-by-value, , if case, have expected original way work.
so i'm confused again, , i'd ask - did line of thought go wrong? ruby pass-by-value in cases? have misunderstood pass-by-value/reference means? issue not related pass-by-value/reference @ all?
you can see object in ruby reference data. if ruby pass value, thing got copy object, a.k.a handle underlining data.
even answer link to, had said:
variables references objects. in order object won't change out under you, need dup or clone object you're passed, giving object nobody else has reference to. (even isn't bulletproof, though — both of standard cloning methods shallow copy, instance variables of clone still point same objects originals did. if objects referenced ivars mutate, still show in copy, since it's referencing same objects.)
Comments
Post a Comment