Ruby - Using iterator for nested array

Description

Using iterator for nested array

Demo

multiarr =
 [ ['one','two','three','four'],
   [1,    2,    3,      4     ],#  ww w.  j av a2s  .  c  om
   [:a,   :b,   :c,    :d     ]
 ]

multiarr.each{ |arr|
    multiarr[0].length.times{|i|
        puts(arr[i])
    }
}

Result

The code above iterates over each element (or "row") of multiarr.

Then iterating along each item in that row by obtaining the row length and using the Integer's times method with that value.

The following code reverses these operations.

The outer block iterates along the length of row 0, and the inner block obtains the item at index i in each row.

Demo

multiarr =
 [ ['one','two','three','four'],
   [1,    2,    3,      4     ],#   w w  w .  j  a va2  s  .c  o m
   [:a,   :b,   :c,    :d     ]
 ]

multiarr[0].length.times{|i|
    multiarr.each{ |arr|
        puts(arr[i])
    }
}

Result

Related Topic