Mateusz Bartkowski Mateusz Bartkowski - 3 years ago 158
Ruby Question

Using each for object with an array of objects

I have an object

@cars = Cars
that has an array
car_array
of objects
Car
that have instance variables
@id
and
@mileage
, so, writing it as pseudo array it's:

Cars = [
Car1 = [1, 12000],
Car2 = [2, 33000]
]


Is there a way to write an
each
method to iterate over the cars, in this way:

@cars.each do |id, mileage|
...
end


?

I've tried to do a custom
each
method in
Cars
:

def each(&block)
@car_array.each(&block)
end


but that would only return each
Car
object into the enumerator. How would I then convert each
Car
object to an array?

Answer Source

In ruby we do chain methods to accomplish different complicated transforms:

@cars.map do |car|
  [car.id, car.mileage]
end.each do |id, mileage|
    ...
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download