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.
> grid = [["... " * 3] * 3, ""].flatten * 3
This produces the desired output
> 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(&:clone)
Is there a better way?
The main question here is how best to make sure each array element is a separate string instance.