5

I have list of user profiles. I need to sort the user profile based on following criteria as shown below:

profile_claimed(boolean) -> profile_complete_status(integer) -> No_of_friends(integer)

code:

user_profiles.sort { |x| [x.claim ? 0 : 1, x.complete_profile_status, x.no_of_friends] }

How to sort the user profile?

1

2 Answers 2

8

You could use sort_by:

user_profiles.sort_by do |x| 
  [(x.claim ? 0 : 1), x.complete_profile_status, x.no_of_friends]
end

Also, it is worth noting that sort_by is usually faster than sort because it caches the result of the comparison operation, which in this case is

(x.claim ? 0 : 1), x.complete_profile_status, x.no_of_friends

and does not recalculate the values for each comparison between two elements.

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

Comments

1

You need to use sort method with block:

ary.sort do |x,y|
  if x > y
    1
  elsif x < y
    -1
  else
    0
  end
end

Just make sure to return +1 when x follows y, -1 when y follows x, or 0 when they are equal.

http://ruby-doc.org/core-2.2.0/Array.html#method-i-sort

1 Comment

While sort is the basic building block for sorting, it often falls down badly when the values being sorted have to be computed or dug out of a structure or object. Instead, use sort_by, which uses a Schwarzian Transform, resulting in major speed improvements.

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.