dogs = names.zip(breeds).map { |name, breed| Dog.new(name, breed) }
Array#zip interleaves the target array with argument elements, so
irb> [1, 2, 3].zip(['a', 'b', 'c']) #=> [ [1, 'a'], [2, 'b'], [3, 'c'] ]
You can use arrays of different lengths (in this case, the target array determines the length of the resulting array, and additional entries are filled using nil ).
irb> [1, 2, 3, 4, 5].zip(['a', 'b', 'c']) #=> [ [1, 'a'], [2, 'b'], [3, 'c'], [4, nil], [5, nil] ] irb> [1, 2, 3].zip(['a', 'b', 'c', 'd', 'e']) #=> [ [1, 'a'], [2, 'b'], [3, 'c'] ]
You can also archive more than two arrays:
irb> [1,2,3].zip(['a', 'b', 'c'], [:alpha, :beta, :gamma])
Array#map is a great way to transform an array, since it returns an array where each record is the result of starting a block in the corresponding record in the target array.
irb> [1,2,3].map { |n| 10 - n }
When using iterators over arrays of arrays, if you give several blocks of parameters, the array records will be automatically divided into these parameters:
irb> [ [1, 'a'], [2, 'b'], [3, 'c'] ].each { |array| p array } [ 1, 'a' ] [ 2, 'b' ] [ 3, 'c' ] #=> nil irb> [ [1, 'a'], [2, 'b'], [3, 'c'] ].each do |num, char| ...> puts "number: #{num}, character: #{char}" ...> end number 1, character: a number 2, character: b number 3, character: c #=> [ [1, 'a'], [2, 'b'], [3, 'c'] ]
As Matt Briggs mentioned , #each_with_index is another good tool to be aware of. It iterates through the elements of the array, passing each element in turn.
irb> ['a', 'b', 'c'].each_with_index do |char, index| ...> puts "character #{char} at index #{index}" ...> end character a at index 0 character b at index 1 character c at index 2
When using an iterator such as #each_with_index , you can use parentheses to split the elements of the array into its component parts:
irb> [ [1, 'a'], [2, 'b'], [3, 'c'] ].each_with_index do |(num, char), index| ...> puts "number: #{num}, character: #{char} at index #{index}" ...> end number 1, character: a at index 0 number 2, character: b at index 1 number 3, character: c at index 2