Ruby - Array Arrays Iterating

Introduction

You can access the elements of an array by iterating over them using a for loop.

In Ruby, to for loop over all the items in a collection, use for..in loop.

Demo

multiarr = [['one','two','three','four'],[1,2,3,4]] 
for i in multiarr 
    puts(i.inspect)  # w  w  w  . j av a2s . co  m
end

Result

To iterate over the items in each of the two subarrays.

If there is a fixed number of items, you could specify a different iterator variable for each, in which case each variable will be assigned the value from the matching array index.

Demo

multiarr = [['one','two','three','four'],[1,2,3,4]] 
for (a,b,c,d) in multiarr 
    print("a=#{a}, b=#{b}, c=#{c}, d=#{d}\n" ) 
end#   ww  w .ja  va 2s.  c o  m

Result

You could use a for loop to iterate over all the items in each subarray individually:

Demo

multiarr = [['one','two','three','four'],[1,2,3,4]] 

for s in multiarr[0]  
   puts(s) #  ww w  .ja  v  a 2s .  com
end 
for s in multiarr[1]  
   puts(s) 
end

Result

To iterate over multidimensional arrays, you could use nested for loops.

An outer loop iterates over each row (subarray), and an inner loop iterates over each item in the current row.

This technique works even when subarrays have varying numbers of items:

Demo

multiarr = [['one','two','three','four'],[1,2,3,4]] 
for row  in multiarr 
   for item in row 
     puts(item)  # from  w ww.jav  a 2 s.  c  o  m
   end 
end

Result

Related Topic