Lance Pollard
Lance Pollard

Reputation: 79450

One-liner for sorting small array by a large array containing same values in Ruby?

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?

Upvotes: 1

Views: 319

Answers (3)

Joshua Cheek
Joshua Cheek

Reputation: 31776

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).

Upvotes: -1

Kyle Sletten
Kyle Sletten

Reputation: 5413

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

Upvotes: 1

sawa
sawa

Reputation: 168229

I think this is what you want:

a & b

Upvotes: 11

Related Questions