红宝石/从定义的索引对哈希数组进行排序 [英] ruby / sort an array of hashes from a defined index

查看:89
本文介绍了红宝石/从定义的索引对哈希数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'},
]

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

I'd like the first array to be a "rule" to sort my second array (probably by matching the id key).

我怎样才能干净利落地做到这一点?

How can i get achieve this cleanly ?

推荐答案

朴素的方法:

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

这篇关于红宝石/从定义的索引对哈希数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆