简体   繁体   English

使用nil键和数组值对哈希排序

[英]Sort hash with nil key and array values

I have a hash like this (it is the result of the group_by method): 我有一个像这样的哈希(它是group_by方法的结果):

{nil => [#<ActiveRecord id ..., ...], #<ActiveRecord ...> => [#<ActiveRecord id ..., ...], ...}

I need to sort it so that the nil elements would be the first, and then all the other ActiveRecord objects. 我需要对其进行排序,以使nil元素成为第一个元素,然后是所有其他ActiveRecord对象。 How can I do this? 我怎样才能做到这一点? Thanx 感谢名单

PS PS

  1. Yes, I need an ActiveRecord objects as the keys (not symbols or some else) 是的,我需要一个ActiveRecord对象作为键(不是符号或其他符号)
  2. I can't do the order in my DB due to complex SQL request. 由于复杂的SQL请求,我无法在数据库中执行订单。

I need only to sort the hash by the keys. 我只需要按键对哈希排序。

You cannot sort a hash, but : 您无法对哈希进行排序, 但是

Hashes enumerate their values in the order that the corresponding keys were inserted. 哈希值按插入相应键的顺序枚举其值。

To get a specific key at the beginning, just make sure to insert it first. 要在开始时获取特定的密钥,只需确保先插入它即可。 Here's an example: 这是一个例子:

array = [Integer, Range, BasicObject]

hash = array.group_by(&:superclass)
#=> {Numeric=>[Integer], Object=>[Range], nil=>[BasicObject]}

To get nil first, create a hash with a nil key and merge! 要首先获取nil ,请使用nil键创建一个哈希并merge! the new values: 新值:

hash = {nil => nil}
hash.merge!(array.group_by(&:superclass))
#=> {nil=>[BasicObject], Numeric=>[Integer], Object=>[Range]}

Assuming you have your hash in h : 假设您在h有哈希:

Hash[h.sort { |a,b| 
  NilClass === a.first ? 
      (NilClass === b.first ? 0 : -1) : 
      (NilClass === b.first ? 1 : a.first <=> b.first) 
}]

Here we explicitly define sort function, which will place nil s in front, following by native ordering of other elements by keys ( ActiveRecord instances in your case.) 在这里,我们明确定义了sort函数,该函数将nil放在前面,然后通过键对其他元素进行本机排序(在您的情况下为ActiveRecord实例)。

Sidenote: you always can do sorting in database. 旁注:您始终可以在数据库中进行排序。

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

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