Is it possible to sort multidimensional hashes using hash values โ€‹โ€‹of child elements?

Is it possible to sort the hash hash by the values โ€‹โ€‹of the child keys?

For instance:

{
    :a => 
        {:order => 3},
    :b =>
        {:order => 1},
    :c =>
        {:order => 2}
}

is used

{
    :b => 
        {:order => 1},
    :c =>
        {:order => 2},
    :a =>
        {:order => 3}
}
+4
source share
2 answers

You can convert it to an array of pairs, use the method sort_byto target the value you want to sort, and then convert it back to a hash:

h = {
    :a => 
        {:order => 3},
    :b =>
        {:order => 1},
    :c =>
        {:order => 2}
}

h.sort_by {|k,v| v[:order]}.to_h
=> {:b=>{:order=>1}, :c=>{:order=>2}, :a=>{:order=>3}} 
+4
source

Keep in mind that the only order that a Ruby hash character can have is based on the insertion order. You need to create a new hash (no sort!) and create a new hash element by element in the order you want.

Given:

> hash
=> {:a=>{:order=>3}, :b=>{:order=>1}, :c=>{:order=>2}}

You can use .sort_byto execute:

> hash.sort_by {|k, h| h[:order]}.to_h
=> {:b=>{:order=>1}, :c=>{:order=>2}, :a=>{:order=>3}}

.sort <=>, , a,b:

> hash.sort {|(a,ha),(b,hb)| ha[:order] <=> hb[:order] }.to_h
=> {:b=>{:order=>1}, :c=>{:order=>2}, :a=>{:order=>3}}

.to_h , .

+4

Source: https://habr.com/ru/post/1681836/


All Articles