![](/img/trans.png)
[英]Ruby : How to sort an array of hash in a given order of a particular key
[英]How to sort an array in Ruby to a particular order?
我想按照另一個數組中給出的特定順序對數組進行排序。
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
包含的所有元素a
,如果元素是唯一的,則:
puts b & a
假設a
將根據b
中元素的順序進行排序
sorted_a =
a.sort do |e1, e2|
b.index(e1) <=> b.index(e2)
end
我通常使用它來按照表單上字段的出現順序對ActiveRecord
中的錯誤消息進行排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.