我有一个哈希数组,我需要根据两个不同的键值对进行排序.
这是我要排序的数组:
array_group = [
{operator: OR, name: "some string", status: false},
{operator: AND, name: "other string", status: false},
{operator: _NOT_PRESENT, name: "another string", status: true},
{operator: AND, name: "just string", status: true}
]
Run Code Online (Sandbox Code Playgroud)
我想排序array_group所以我有status: true第一个项目,然后是status: false,然后是项目,operator: _NOT_PRESENT最后根据名称对其进行排序,结果如下:
array_group = [
{operator: AND, name: "just string", status: true},
{operator: AND, name: "other string", status: false},
{operator: OR, name: "some string", status: false},
{operator: _NOT_PRESENT, name: "another string", status: true},
]
Run Code Online (Sandbox Code Playgroud)
有没有办法可以在不创建子数组并对其进行排序并将它们连接起来的情况下完成此操作?
您还可以使用Enumerable#sort_by.该示例构建一个数组,在排序时逐个元素进行比较.
array_group.sort_by { |e| [e[:operator] == "_NOT_PRESENT" ? 1 : 0,
e[:status] ? 0 : 1,
e[:name]] }
Run Code Online (Sandbox Code Playgroud)
上面的例子operator: "_NOT_PRESENT"也用by 命令记录:status.以下代码段精确地执行了问题的排序.
def priority(h)
case
when h[:operator] == "_NOT_PRESENT" then 3
when h[:status] == false then 2
# h[:status] == true
else 1
end
end
array_group.sort_by { |e| [priority(e), e[:name]] }
Run Code Online (Sandbox Code Playgroud)