Clone array elements when multiplying by a scalar I am building an array of strings to form the "empty" representation of a puzzle onto which I will overwrite single characters as necessary for debugging purposes. However, building the array using scalar multiplication results in shared string instances among the rows which breaks when I modify them.

&gt; grid = [["... " * 3] * 3, ""].flatten * 3


This produces the desired output


&gt; puts grid * "\n"

... ... ...
... ... ...
... ... ...

... ... ...
... ... ...
... ... ...

... ... ...
... ... ...
... ... ...



But the array contains only two string instances: nine of "... ... ..." and two of "". To solve this I use map to clone each string:

grid = ([["... " * 3] * 3, ""].flatten * 3).map(&amp;:clone)


Is there a better way?

The main question here is how best to make sure each array element is a separate string instance.
I might do this:

grid = 9.times.map { "... " * 3 }


Or, better yet, as Naklion proposes in the comments:

grid = Array.new(9) { "... " * 3 }


to get the rows (as separate string instances), and this

grid.each_slice(3) { |rows| puts rows, "\n"  }


to print it similar to yours. But I wouldn't call either approach "idiomatic", just variations on a theme. I don't know if anything really idiomatic can be said to exist for this

However, it might be easier to approach this from a higher level, rather than rely on a string representation. I.e. parse the input grid into Cell, Row etc. objects (I'm obviously assuming this is sudoku we're talking about).
Of course, if you have a clever idea that relies on string manipulation, then go for it!

My point is more that I know you can get far with, say, bitwise representations of sudoku, but implementing that in Ruby (while totally possible) seems "crude". Ruby's not geared toward twiddling bits, but toward more high-level OOP abstractions. It'd be right at home in C/C++, though.

*) I'd go with "rubyesque" or just "ruby" as in "the ruby way of doing things" :)