Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Frequency of value in Ruby hash

If I have a hash of book ratings like

books = {"Gravity's Rainbow"=>:splendid,
         "House in Hyde Park"=>:splendid, 
         "The Week"=>:quite_good
        }

and I want to count the number of occurrences of a particular value, or rating, how is this done?

I tried books.values[:splendid].length - but I suppose the error is brought about because it thinks I want to slice everything up to "splendid", which is of the wrong type, from "books.values".

How do I remove everything not ":splendid" from books.values? Should I be looking at list operations rather than hash? I'm totally new to Ruby, thinking as I type. I'm not sure if books.values has returned a list or some other type though?

like image 261
OJFord Avatar asked Dec 19 '22 23:12

OJFord


1 Answers

books.values returns an array:

books.values
#=> [:splendid, :splendid, :quite_good]

So you can just use Array#count:

books.values.count(:splendid)
#=> 2

Or something like this to count all values:

Hash[books.group_by { |k, v| v }.map { |k, v| [k, v.count] }]
#=> {:splendid=>2, :quite_good=>1}
like image 190
Stefan Avatar answered Jan 09 '23 10:01

Stefan