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.