0
cars = Car.find(data).find_all{ |car| car.model == "Honda" }

this returns a list of Car's--I'd like to convert this list to a list that only contains the car.id's. How would I do it in a Ruby like way?

3 Answers 3

2

Simply call:

cars = Car.find(data).find_all{ |car| car.model == "Honda" }.map{ |car| car.id }

http://corelib.rubyonrails.org/classes/Array.html#M000427

Sign up to request clarification or add additional context in comments.

Comments

2

You can do this:

car_ids = Car.find(data).find_all{ |car| car.model=="Honda" }.map{ |car| car.id }

Essentially, array.map { |x| f(x) } returns a new array of identical size, which contains the result of calling f on each of the original array's entries, in the same order.

Comments

1

I'd do it like that:

cars = Car.where(id: data, model: 'Honda').pluck(:id)

assuming that data is an array of car id's

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.