Multiple Iterator Arguments

In the previous chapter, you used a 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 (that is, one “subarray”) from the outer array:

multi_array.rb

# Here multiarr is an array containing two 'rows'
# (subarrays) at index 0 and 1
multiarr = [    ['one','two','three','four'],
                [1,2,3,4]
           ]
# 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}
" )
end

The previous loop prints this:

a=one, b=two, c=three, d=four
a=1, b=2, c=3, d=4

However, you could also 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:

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

And, of course, the alternative block syntax, delimited by curly brackets, works just as well:

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

Both of the previous examples pass the two elements from the multiarr array into the iterator block. The first element is itself an array of four strings: ['one','two','three','four']. Since the block has four parameters declared between a pair of upright bars, |a,b,c,d|, the four strings are assigned to the matching parameters, which are then printed with the print statement. Then the each method passes the second element of multiarr into the block. This is another four-element array, this time containing integers: [1,2,3,4]. These are again assigned to the block parameters, |a,b,c,d|, and the print statement displays them. Note that the output is identical as when you used the for loop:

a=one, b=two, c=three, d=four
a=1, b=2, c=3, d=4
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.102.50