Basic Array Iteration in Ruby
Posted
by michaelmichael
on Stack Overflow
See other posts from Stack Overflow
or by michaelmichael
Published on 2010-04-15T20:41:14Z
Indexed on
2010/04/15
20:43 UTC
Read the original article
Hit count: 329
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 = 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?
© Stack Overflow or respective owner