Reputation: 26525
To iterate through the elements in a single dimensional array, I can use
array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }
Is there any way I to do this for a nested list or a two dimensional array? In this code:
two_d_array = [[1,2], [3,4], [5,6]]
two_d_array.each{|array| puts array}
I wish to get [1, 2], [3, 4], [5, 6]
so that I can access each element of the list separately and do some operation on it such as array[1] = "new_value"
, but it gives 123456
I want to avoid using matrix if possible.
Upvotes: 2
Views: 1929
Reputation: 11705
Actually the each
block does behave in the way you expect, but the puts
command makes it look as though the array has been pre-flattened. If you add an inspect
, this becomes clear:
>> two_d_array.each{|array| puts array.inspect}
[1, 2]
[3, 4]
[5, 6]
So the array
variable in each iteration will be the nested array element.
Upvotes: 6