Screw diamonds. Ruby is a girl's best friend.

Surfing the waters of programming

Sorting Hash Values

| Comments

Have a huge Array of hashed and need to find how many times the same event occur?

1
2
3
h = [ {"a" => 10}, {"b" => 20}, {"a" => 10}, {"b" => 20}, {"c" => 30}, {"a" => 10} ]
count_h = h.inject(Hash.new(0)){ |hash, i| hash[i] += 1; hash }
puts h                 #=> {{"a"=>10}=>3, {"b"=>20}=>2, {"c"=>30}=>1} 

Looking for awesome ways to sort Hash by its values?

1
2
3
h = {{"a"=>10}=>3, {"c"=>30}=>1, {"b"=>20}=>2}
Hash[h.sort_by {|key, value| -value }] #=> will sort in descending order
p h #=> {{"a"=>10}=>3, {"b"=>20}=>2, {"c"=>30}=>1} 

Comments