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?
I think this is what you want:
a & b
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
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).
精彩评论