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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.