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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With