source_array = Array.new(5) { Array.new(10) }
source_array[3][4] = 0
source_array[2][5] = 1
source_array[4][2] = 0.5
Now, to create a new array destination_array of the same dimensions as source_array. destination_array contains the values 0 and 1 only. Any non-nil value in source_array maps to 1 in destination_array, and all nil values map to 0.
destination_array = Array.new(5) { Array.new(10, 0) }
...
What is the best way to do this in Ruby (1.9.2)?
Omit:
And instead use:
This will give you what you want.
The key here is to let the iteration function
Array#mapperform the work for you, that way you don’t have to worry about indexes. This will work for any 2-dimensional array where you want the same dimensions for the input and output arrays.