Hi. First-time poster here. I’ve done some programming in Delphi
before (like 10 years ago), and I wanted to get back to programming as a
hobby. I’ve looked at several languages, and Ruby looked the funnest.
So here I am.
For my first project, I’ve decided to make a Sudoku class, making it
general enough so that it can easily be subclassed to implement many
Sudoku variations out there.
To store the board state, I decided to make an instance variable @board
which is a two-dimensional array of 9x9. And there would be several
methods that will manipulate the board.
Then it occurred to me that it would be nice to have a .revert method
that will revert the board to its initial state.
Easy enough, I thought.
To the .initialize method, I added the line:
@initialboard = @board
and I added a new .revert method which did:
@board = @initialboard
And this, as you Ruby-experts may imagine, is where I came to
face-to-face with Ruby’s “variables are references, not containers”
nature. Every time I manipulated @board, the “content” of @initialboard
would get altered as well, making it useless as a backup of the initial
state of the board.
I’ve tried .dup and .clone methods, but it didn’t work because @board
was a two-dimensional, array-within-array structure. .dup and .clone
methods only duplicated the top level array, and the sub-level arrays
were still being referenced to the same data, leading to the same result
as the first time around.
So here’s my question. Is there a simple and elegant way to duplicate
the entire content of a multi-dimensional array?
Right now, the only workarounds I can think of are: 1) store the data in
one long one-dimensional array, of 2) use an iterator to duplicate each
sub-level arrays individually. Neither are very elegant nor attractive.
Thanks in advance to any insight you guys can give me in this matter.
Oh, one more question: what’s the difference between .dup and .clone