开发者

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

开发者 https://www.devze.com 2023-02-26 22:02 出处:网络
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?

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号