B Seven
B Seven

Reputation: 45943

How to project 2D array into new array in Ruby?

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)?

Upvotes: 1

Views: 465

Answers (2)

TreyE
TreyE

Reputation: 2739

Omit:

destination_array = Array.new(5) { Array.new(10, 0) }

And instead use:

destination_array = source_array.map { |subarray| subarray.map { |item| item.nil? ? 0 : 1 } }

This will give you what you want.

The key here is to let the iteration function Array#map perform 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.

Upvotes: 3

Platinum Azure
Platinum Azure

Reputation: 46193

destination_array = source_array.map { |arr| arr.map { |elem| elem.nil? ? 0 : 1 } }

Upvotes: 2

Related Questions