简体   繁体   English

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

[英]How to sort an array in Ruby to a particular order?

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', ie 现在我想按'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? 有什么建议么?

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

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

puts b & a

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中的错误消息进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM