问题
I have an array of hashes which I'd like to sort by one of the values. However, if two hashes have the same value if like to sort them on a second (backup) value.
In the example below I'd like to sort the hashes based of the value of "a". If two elements have the same value for "a" I'd like to sort by the value of "b" as a backup.
# Notice the first and last hashes have the same value for "a"
hashes = [
{a: 2, b: 7},
{a: 1, b: 0},
{a: 9, b: 6},
{a: 2, b: 8}
]
Output
{a: 1, b: 0},
{a: 2, b: 7},
{a: 2, b: 8},
{a: 9, b: 6}
回答1:
I think this is pretty easy with using of #sort_by with #values_at
hashes.sort_by { |e| e.values_at(:a, :b) }
=> [{:a=>1, :b=>0},
{:a=>2, :b=>7},
{:a=>2, :b=>8},
{:a=>9, :b=>6}]
it also might be expanded, for example, you have array of hashes with 3 keys:
hashes = [
{a: 2, b: 7, c: 8},
{a: 1, b: 0, c: 5},
{a: 9, b: 6, c: 6},
{a: 2, b: 7, c: 3}
]
then:
hashes.sort_by { |e| e.values_at(:a, :b, :c) }
=> [{:a=>1, :b=>0, :c=>5},
{:a=>2, :b=>7, :c=>3},
{:a=>2, :b=>7, :c=>8},
{:a=>9, :b=>6, :c=>6}]
回答2:
Try the below:
hashes.sort { |hash1, hash2| [hash1[:a], hash1[:b]] <=> [hash2[:a], hash2[:b]]}
来源:https://stackoverflow.com/questions/63987833/sort-array-of-hashes-based-on-two-properties