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}\n" ) 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 ...
Get The Book of Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.