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.
Actually the
eachblock does behave in the way you expect, but theputscommand makes it look as though the array has been pre-flattened. If you add aninspect, this becomes clear:So the
arrayvariable in each iteration will be the nested array element.