简体   繁体   English

红宝石/从定义的索引对哈希数组进行排序

[英]ruby / sort an array of hashes from a defined index

Having the following array, it defines the sorting : 具有以下数组,它定义了排序:

[300, 450, 345, 23]

And the following array, unsorted : 和以下数组,未排序:

[
  {id: 450, title: 'rand1'},
  {id: 23, title: 'rand3'},
  {id: 300, title: 'rand0'},
  {id: 345, title: 'rand2'},
]

I'd like the first array to be a "rule" to sort my second array (probably by matching the id key). 我希望第一个数组成为对第二个数组进行排序的“规则”(可能通过匹配id键)。

How can i get achieve this cleanly ? 我怎样才能做到这一点呢?

Naïve approach: 幼稚的方法:

sorter = [300, 450, 345, 23]
input = [
   {id: 450, title: 'rand1'},  
   {id: 23, title: 'rand3'},  
   {id: 300, title: 'rand0'},  
   {id: 345, title: 'rand2'},  
]  
input.sort do |h1, h2|
  sorter.index(h1[:id]) <=> sorter.index(h2[:id])
end
#⇒ [
#     {:id=>300, :title=>"rand0"},
#     {:id=>450, :title=>"rand1"},
#     {:id=>345, :title=>"rand2"},
#     {:id=>23, :title=>"rand3"}]

or even simper: 甚至更简单:

input.sort_by { |h| sorter.index(h[:id]) }

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

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