如何排序在Ruby中一个特定的顺序数组? [英] How to sort an array in Ruby to a particular order?
本文介绍了如何排序在Ruby中一个特定的顺序数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要排序在另一个数组给出特定的顺序数组。
I want to sort an array in particular order given in another array.
EX:考虑数组
a=["one", "two", "three"]
b=["two", "one", "three"]
现在我想排序数组'A'中的'B',即
Now I want to sort array 'a' in the order of 'b', i.e
a.each do |t|
# It should be in the order of 'b'
puts t
end
所以输出应该是
two
one
three
有什么建议?
推荐答案
阵列#sort_by是你追求的。
Array#sort_by is what you're after.
a.sort_by do |element|
b.index(element)
end
在响应更具扩展性的版本评论:
More scalable version in response to comment:
a=["one", "two", "three"]
b=["two", "one", "three"]
lookup = {}
b.each_with_index do |item, index|
lookup[item] = index
end
a.sort_by do |item|
lookup.fetch(item)
end
这篇关于如何排序在Ruby中一个特定的顺序数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文