0

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?

0

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.