1

Say I have 2 arrays like this:

# base set
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# sub set
b = [5, 1, 8, 3]

What's the optimal way to sort b to the same order as a?

a.sort_like(b) #=> [1, 3, 5, 8]

What is this operation called?

4
  • 1
    Your receiver and the argument is strange. It would be more natural if it were the other way around. Commented Apr 19, 2011 at 23:58
  • either way works for me. Commented Apr 19, 2011 at 23:59
  • using this in the code right now, love it. Commented Apr 20, 2011 at 0:05
  • possible duplicate of How to sort an array in Ruby to a particular order? Commented Apr 20, 2011 at 2:35

3 Answers 3

11

I think this is what you want:

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

1 Comment

The operation is called "set intersection", and does not sort, but it just removes from (the dup of) the receiver what's not in the argument. You can go with randomguy's naming.
1

This will do it, I'm not sure about the most efficient way.

def sort_like(other)
  items = []
  other.each do |find|
    each do |item|
      items.append item if item == find
    end
  end
  items
end

Comments

-1

If b is a subset of a, as you have defined, then the result is going to always be the sorted version of b. In which case, the you just want b.sort (it won't mutate b, it will return a new array with the sorted contents of b).

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.