ruby /从定义的索引中对哈希数组进行排序

问题描述 投票:0回答:1

拥有以下数组,它定义了排序:

[300, 450, 345, 23]

以下数组,未分类:

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

我希望第一个数组成为对我的第二个数组进行排序的“规则”(可能是通过匹配id键)。

我怎样才能干净利落地实现这一目标?

arrays ruby sorting
1个回答
5
投票

天真的做法:

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"}]

甚至简单:

input.sort_by { |h| sorter.index(h[:id]) }
© www.soinside.com 2019 - 2024. All rights reserved.