2

I have a collection of a model. I want to perform some complex sorting logic on this collection. The logic is not as simple as sorting based on a simple attribute. What the best way (performance and maintainability wise) to perform complex sorting logic on a collection of models. I am thinking along the lines of passing in a block to the sort method? But I am not sure...

Thanks.

2 Answers 2

4

Yes, you can use a block using sort_by

@people.sort_by { |person| person.age }

sort_by uses the Schwartzian transform internally in sort_by, so if your logic is a little more complex than that, you can still create a scoring function and pass it to sort_by

@people.sort_by do |person|
  tier = if person.deceased?
    2
  elsif !person.important?
    1
  else
    0
  end
  [tier, person.age
end

Ask yourself if you can't make the sorting directly from the SQL query, this will be a lot faster (assuming the right query and indices)

@people = Person.all(:select => "*, (age + popularity) as coolness", :order => "coolness")
Sign up to request clarification or add additional context in comments.

Comments

1

I'd advise you to read this resource, this chapter in particular:

#21 Using Procs for Filtering (matching_members.rb)

There are great filtering examples given using Procs and blocks.

PS: yes I'd use blocks even if your question is a bit vague.

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.