ruby - How do I sort a hash with the highest specific value? -
ruby - How do I sort a hash with the highest specific value? -
i have hashes within array nammed elem
, , must "type" keys have highest "count" value.
i know enumerators great thing know, don't understand them well.
elem = [{"type"=>"dododo", "count"=>0, "name"=>"dododo's", "tip"=>"dododo's level"}, {"type"=>"dadada", "count"=>1203, "name"=>"dadada's", "tip"=>"dadada's degree"}, {"type"=>"dedede", "count"=>717, "name"=>"dedede's", "tip"=>"dedede's degree"}, {"type"=>"dididi", "count"=>6, "name"=>"dididi's", "tip"=>"dididi or professional degree"}]
i'm trying this:
elem.each |i| i.each_with_index |k,v| puts v["count"] end end
but know i've missed step.
i know these kind of "manoeuvre" comon , of import know.
one way utilize enumerable#max_by
elem = [ {"type"=>"dododo", "count"=>0, "name"=>"dododo's", "tip"=>"dododo's level"}, {"type"=>"dadada", "count"=>1203, "name"=>"dadada's", "tip"=>"dadada's degree"}, {"type"=>"dedede", "count"=>717, "name"=>"dedede's", "tip"=>"dedede's degree"}, {"type"=>"dididi", "count"=>6, "name"=>"dididi's", "tip"=>"dididi or professional degree"} ] max_elem = elem.max_by {|e| e['count']} puts max_elem['type'] # returns dadada
ruby arrays sorting hash enums
Comments
Post a Comment