Ruby - 基于数组顺序对哈希值(字符串)进行排序

Kur*_*t W 2 ruby arrays

我有一个以下所示格式的哈希数组,我试图:book根据一个单独的数组对哈希的键进行排序.订单不是按字母顺序排列的,对于我的用例,它不能按字母顺序排列.

我需要根据以下数组进行排序:

array = ['Matthew', 'Mark', 'Acts', '1John']
Run Code Online (Sandbox Code Playgroud)

请注意,我已经看到了一些利用的解决方案Array#index(例如,基于排序值数组对哈希数组进行排序)来执行自定义排序,但这不适用于字符串.

我试着整理的各种组合Array#sortArray#sort_by,但他们似乎并不接受客户订单.我错过了什么?预先感谢您的帮助!

哈希数组

[{:book=>"Matthew",
  :chapter=>"4",
  :section=>"new_testament"},
 {:book=>"Matthew",
  :chapter=>"22",
  :section=>"new_testament"},
 {:book=>"Mark",
  :chapter=>"6",
  :section=>"new_testament"},
 {:book=>"1John",
  :chapter=>"1",
  :section=>"new_testament"},
 {:book=>"1John",
  :chapter=>"1",
  :section=>"new_testament"},
 {:book=>"Acts",
  :chapter=>"9",
  :section=>"new_testament"},
 {:book=>"Acts",
  :chapter=>"17",
  :section=>"new_testament"}]
Run Code Online (Sandbox Code Playgroud)

max*_*ner 5

这是一个例子

arr = [{a: 1}, {a: 3}, {a: 2}] 

order = [2,1,3]  

arr.sort { |a,b| order.index(a[:a]) <=> order.index(b[:a]) }                                           
# => [{:a=>2}, {:a=>1}, {:a=>3}]  
Run Code Online (Sandbox Code Playgroud)

在你的情况下,它会

order = ['Matthew', 'Mark', 'Acts', '1John']
result = list_of_hashes.sort do |a,b|
  order.index(a[:name]) <=> order.index(b[:name])
end
Run Code Online (Sandbox Code Playgroud)

这里有两个重要的概念:

  1. 使用Array#index以找到在数组中的元素被发现
  2. "宇宙飞船运营商" <=>是如何Array#sort运作的 - 看什么是Ruby <=>(宇宙飞船)运营商?

您可以通过索引要按顺序排列的元素列表来使其快一些:

order_with_index = order.each.with_object.with_index({}) do |(elem, memo), idx|
  memo[elem] = idx
end
Run Code Online (Sandbox Code Playgroud)

然后而不是order.index(<name>)使用order_with_index[<name>]