如何将Ruby中的数组排序为特定的顺序?

时间:2022-01-31 14:39:45

I want to sort an array in particular order given in another array.

我想按照另一个数组中给出的特定顺序对数组进行排序。

EX: consider an array

EX:考虑一个数组

a=["one", "two", "three"]
b=["two", "one", "three"]

Now I want to sort array 'a' in the order of 'b', i.e

现在我想按'b'的顺序对数组'a'进行排序,即

a.each do |t|
  # It should be in the order of 'b'
  puts t
end

So the output should be

所以输出应该是

two
one 
three 

Any suggestions?

有什么建议么?

3 个解决方案

#1


46  

Array#sort_by is what you're after.

数组#sort_by就是你所追求的。

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

#2


12  

If b includes all elements of a and if elements are unique, then:

如果b包含a的所有元素,并且if元素是唯一的,则:

puts b & a

#3


9  

Assuming a is to be sorted with respect to order of elements in b

假设a将根据b中元素的顺序进行排序

sorted_a = 
a.sort do |e1, e2|
  b.index(e1) <=> b.index(e2)
end

I normally use this to sort error messages in ActiveRecord in the order of appearance of fields on the form.

我通常使用它来按照表单上字段的出现顺序对ActiveRecord中的错误消息进行排序。

#1


46  

Array#sort_by is what you're after.

数组#sort_by就是你所追求的。

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

#2


12  

If b includes all elements of a and if elements are unique, then:

如果b包含a的所有元素,并且if元素是唯一的,则:

puts b & a

#3


9  

Assuming a is to be sorted with respect to order of elements in b

假设a将根据b中元素的顺序进行排序

sorted_a = 
a.sort do |e1, e2|
  b.index(e1) <=> b.index(e2)
end

I normally use this to sort error messages in ActiveRecord in the order of appearance of fields on the form.

我通常使用它来按照表单上字段的出现顺序对ActiveRecord中的错误消息进行排序。