Forum: Ruby Array Nil, can't figure out why

D508dda73e83bf197830bb1e084896b0?d=identicon&s=25 Nico Envy (envy)
on 2014-08-07 04:41
Attachment: exo.rb (327 Bytes)
The array init becomes nil and so it would never enter the if condition,
any ideas why?
4a65f01f7ece0b720bdb0de3c3db089e?d=identicon&s=25 Dansei Yuuki (blutorange)
on 2014-08-07 08:38
Attachment: exo.png (20 KB)
Attachment: exo.png (30 KB)
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
> end
>
> puts "Woot!!! It took #{i} tries."
D508dda73e83bf197830bb1e084896b0?d=identicon&s=25 Nico Envy (envy)
on 2014-08-07 19:23
Thank you dude ! Very helpful :)
4a65f01f7ece0b720bdb0de3c3db089e?d=identicon&s=25 Dansei Yuuki (blutorange)
on 2014-08-09 08:11
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]]
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.