0

I have a table with 2 columns. "car" "year". I want to do a collect into an array of all cars and then sort them by year. How do I do that?

<% @cars_pre = Car.find(:all) %>
<% @cars = @cars_pre.collect {|x| x.car} %>

I need the steps to order the @cars array by year, keep in mind I am not keeping year values in the @cars array, just cars. Thanks in advance.

2 Answers 2

3

From the code sample, I'm guessing you are using Ruby on Rails. If you are, I would recommend you allow your database to order the results. For example:

@cars = Card.order("year").all
Sign up to request clarification or add additional context in comments.

1 Comment

You even do not need all in this chain.
0

Use sort:

@cars.sort_by!(:year) # in-place sort

Why remove the information by which you wish to sort then sort it by that information? Just keep the information in the array–there's no need to remove it. Plus you need it for the sort.

That said, why not sort it on the DB side using order("year")?

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.