如何将Ruby中的数组排序为特定的顺序?
我想按照另一个数组中给出的特定顺序对数组进行排序。
EX:考虑一个数组
a=["one", "two", "three"] b=["two", "one", "three"]
现在我想按’b’的顺序对数组’a’进行排序,即
a.each do |t| # It should be in the order of 'b' puts t end
所以输出应该是
two one three
有什么建议?
数组#sort_by就是你所追求的。
a.sort_by do |element| b.index(element) end
响应评论的更具可扩展性的版本:
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
如果b
包含b
所有元素,并且if元素是唯一的,则:
puts b & a
假设a
将根据b
中元素的顺序进行排序
sorted_a = a.sort do |e1, e2| b.index(e1) <=> b.index(e2) end
我通常使用它来按照表单上字段的出现顺序对ActiveRecord
中的错误消息进行排序。