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

Ben*_*Ben 0 ruby arrays sorting

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

[300, 450, 345, 23]
Run Code Online (Sandbox Code Playgroud)

以下数组,未分类:

[
  {id: 450, title: 'rand1'},
  {id: 23, title: 'rand3'},
  {id: 300, title: 'rand0'},
  {id: 345, title: 'rand2'},
]
Run Code Online (Sandbox Code Playgroud)

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

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

Ale*_*kin 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"}]
Run Code Online (Sandbox Code Playgroud)

甚至简单:

input.sort_by { |h| sorter.index(h[:id]) }
Run Code Online (Sandbox Code Playgroud)