0

Ruby newbie here... I want to apply Array.map! to an element of a 2D array, but doing something like the example below applies map to every element of the array.

array = Array.new(3, Array.new(3, 0))
array[2].map! { |e| e + 1 }
print array

This gives me [[1, 1, 1], [1, 1, 1], [1, 1, 1]] whereas I want something more like [[0, 0, 0], [0, 0, 0], [1, 1, 1]].

Matt Kuo
  • 43
  • 3

2 Answers2

0

You'll have to map each, for example:

modified = array.map{ |sub| sub.map{ |e| e+1 } }

If you want to mutate in-place:

array.each{ |sub| sub.map!{ |e| e+1 } }

However, you are not creating your initial 2D array correctly. You want:

array = Array.new(3){ Array.new(3) }

…so that the sub-entries are not shared. See the marked-as-duplicate answer in the comment above for more information.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
0

Like @Phrogz said you just need to initialize correctly.

Then you can use your methodology

 array = Array.new(3){ Array.new(3,0)}
 #=> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
 array[2].map!{|e| e + 1}
 #=> [1, 1, 1]
 array
 #=> [[0, 0, 0], [0, 0, 0], [1, 1, 1]]
engineersmnky
  • 25,495
  • 2
  • 36
  • 52