The array init becomes nil and so it would never enter the if condition,
any ideas why?
In ruby, you can think of variables as referencing to objects. When you
write
deck = init = Array(1…cards)
You are creating a new Array object, and let both deck and init point to
that object. During your loop, you are creating a new array, filling it
and emptying the original array.
deck = table
Deck now points to the newly created array, but init still points to the
array created initially, which is now empty.
To fix this, you can write either
deck = Array(1…cards)
init = Array(1…cards)
or
init = Array(1…cards)
deck = init.clone
or if you really want to do it in one line
deck = (init = Array(1…cards)).clone
Your program then outputs
Woot!!! It took 6 tries.
Also, here’s a slightly shorter version of the program:
i = 0
cards = 10
deck = Array(1…cards)
init = Array(1…cards)while init!=deck || i==0
table = []
cards.times do
table.unshift(deck.shift)
deck.push(deck.shift)
end
deck = table
i += 1
endputs “Woot!!! It took #{i} tries.”
Thank you dude ! Very helpful
Perhaps I should add that Array#clone only performs a shallow copy. It
won’t clone any of the array’s elements. Consider the following code
example:
x = [0,1,[2,3]]
y = x.clone
y[0] = 9
y[2][1] = 9
p x
p y
This will produce
[0,1,[2,9]]
[9,1,[2,9]]