What’s a better way to traverse an array while iterating through another array? For example, if I have two arrays like the following:
names = [ "Rover", "Fido", "Lassie", "Calypso"]
breeds = [ "Terrier", "Lhasa Apso", "Collie", "Bulldog"]
Assuming the arrays correspond with one another – that is, Rover is a Terrier, Fido is a Lhasa Apso, etc. – I’d like to create a dog class, and a new dog object for each item:
class Dog
attr_reader :name, :breed
def initialize(name, breed)
@name = name
@breed = breed
end
end
I can iterate through names and breeds with the following:
index = 0
names.each do |name|
Dog.new("#{name}", "#{breeds[index]}")
index = index.next
end
However, I get the feeling that using the index variable is the wrong way to go about it. What would be a better way?
Array#zipinterleaves the target array with elements of the arguments, soYou can use arrays of different lengths (in which case the target array determines the length of the resulting array, with the extra entries filled in with
nil).You can also zip more than two arrays together:
Array#mapis a great way to transform an array, since it returns an array where each entry is the result of running the block on the corresponding entry in the target array.When using iterators over arrays of arrays, if you give a multiple parameter block, the array entries will be automatically broken into those parameters:
Like Matt Briggs mentioned,
#each_with_indexis another good tool to know about. It iterates through the elements of an array, passing a block each element in turn.When using an iterator like
#each_with_indexyou can use parentheses to break up array elements into their constituent parts: