Ruby - Multiple Iterator Arguments

Introduction

You can use for loop with more than one loop variable to iterate over a multidimensional array.

On each turn through the for loop, a variable was assigned one row from the outer array:

Demo

multiarr = [    ['one','two','three','four'], 
                [1,2,3,4] # from  ww  w.  ja  v  a2  s .com
           ] 
# This for loop runs twice (once for each 'row' of multiarr) 
for (a,b,c,d) in multiarr 
   print("a=#{a}, b=#{b}, c=#{c}, d=#{d}\n" ) 
end

Result

You could use the each method to iterate over this four-item array by passing four block parameters-a, b, c, d-into the block delimited by do and end at each iteration:

Demo

multiarr = [    ['one','two','three','four'], 
                [1,2,3,4] # w ww.  j ava2s .c o m
           ] 

multiarr.each do |a,b,c,d|   
   print("a=#{a}, b=#{b}, c=#{c}, d=#{d}\n" )  
end

Result

The alternative block syntax, delimited by curly brackets, works just as well:

Demo

multiarr = [    ['one','two','three','four'], 
                [1,2,3,4] # ww w  . j  a  v a2s .co m
           ] 

multiarr.each{  |a,b,c,d|   
    print("a=#{a}, b=#{b}, c=#{c}, d=#{d}\n" )  
}

Result

Related Topic