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)  # from ww w. j  av a 2s  .com
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# w  w  w .  j ava2  s.c  om

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) # w  w  w .ja va 2s  .  c o m
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)  # w w  w .  j  a v  a2  s . c  o m
   end 
end

Result

Related Topic