1

I have an array of objects and I need to sort them by the values of an attribute. The order to sort is given in the second array.

a = [ object1, object2, object3, object4]

object1.job = 'ER'
object2.job = 'AD'
object3.job = 'WE'
object4.job = 'ER'

b = ['ER', 'ER', 'WE', 'AD']

I need to sort my array a so that it returns [object1/object4, object3, object2]. How can I use my array b as a key for the sorting?

1
  • 1
    Your ordering given by b is contradictory. It means that ER precedes (and follows) itself. Commented Oct 3, 2014 at 19:25

1 Answer 1

4

This should work:

sorted_a = a.sort_by { |obj| b.index obj.job }

Note that b doesn't need to have multiple copies of ER; it just needs to indicate that ER comes before WE and AD.

b = ['ER', 'WE', 'AD']

The index function returns the position of its argument in its invocant:

b.index 'ER'  #=> 0
b.index 'AD'  #=> 2

And the sort_by method runs the supplied block on each element of the array and uses the results as the keys to sort by.

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

1 Comment

Good point about ER. Actually, what OP gave is contradictory. It means that ER precedes (and follows) itself.

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.