5

I have an array of user records, and I would like to sort the users based on priority, which is stored in an array of strings and this array is always changing.

so if i have users =

    User id: 1, username: "so_admin", priority: "Monday"

    User id: 2, username: "so_staff", priority: "Wednesday"

priority = ["Wednesday","Tuesday","Friday"]

How can I sort my users so that users where their priority is "Wednesday" are listed first, etc.

1 Answer 1

9

You can do as

users.sort_by { |u| priority.index(u.priority) || priority.size }

The above sorting is done, with the assumption that the below Array will be sorted as per your need, will hold all uniq values. users array then will use the index of the sorted array.

priority = ["Wednesday","Tuesday","Friday"]

index(obj) → int or nil

Returns the index of the first object in ary such that the object is == to obj. Returns nil if no match is found.

priority array doesn't hold all weekdays, rather 3. I thought, if any users has priority, which is not present in the priority array, let those users be placed in the last array. Suppose, for any user there is a priority, "Sunday", then, that user will be given lowest priority. How ?

Look at the expression priority.index(u.priority) || priority.size, now with above mentioned sample, priority.index("sunday") gives nil, and right hand side expression of the || will be evaluated, i.e. priority.size, which 3. That's how that user will be moved to the tail of the array.

1
  • 1
    wonderful! this worked! thank you! Would you mind explaining what the "priority.size" part does? Commented Jul 29, 2014 at 17:35

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.