Helban Helban - 6 months ago 8
Ruby Question

Ruby on rails. Sort a hash by number of endorsements to display in a chart

I've made a statstics page on which i display a chart with users and number of endorsements they have, which looks like this:
enter image description here

What I want to do now, is to sort the displayed result by the number of endorsements, and not sure how to properly do that.

The @data I am displaying is built like this:

@data = @users.map { |user|
amount = user.inbound_endorsements.joins(:endorsed_user).group(:name).count
if !amount.empty?
{name: user.name, data: amount}
end
}


And in my view,

<%= @data.compact %>


Gives a hash like this:


[{:name=>"Jess Corwin", :data=>{"Jess Corwin"=>1}}, {:name=>"Rhiannon
Nicolas", :data=>{"Rhiannon Nicolas"=>1}}, {:name=>"Assunta Pfeffer",
:data=>{"Assunta Pfeffer"=>2}}, {:name=>"Rafaela Farrell",
:data=>{"Rafaela Farrell"=>1}}, {:name=>"Maurine Hettinger",
:data=>{"Maurine Hettinger"=>1}}]


And I want to sort it by the number.

I've tried diffeerent approaches like:

<%= @data.compact.sort! %>
<%= @data.compact.sort_by{ |name,data| data } %>
<%= @data.compact.sort_by{ |d| d[:data] } %>


and other similiar approaches, most of them result in an error:


comparison of Hash with Hash failed


Any help on how can I accomplish this will be appreciated!

Answer
arr.sort_by { |h| h[:data].values }
=> [{:name=>"Jess Corwin", :data=>{"Jess Corwin"=>1}}, 
    {:name=>"Rhiannon Nicolas", :data=>{"Rhiannon Nicolas"=>1}},        
    {:name=>"Rafaela Farrell", :data=>{"Rafaela Farrell"=>1}}, 
    {:name=>"Maurine Hettinger", :data=>{"Maurine Hettinger"=>1}},
    {:name=>"Assunta Pfeffer", :data=>{"Assunta Pfeffer"=>2}}]
Comments