Calculate sum of objects for each unique object property in Ruby

Posted by macek on Stack Overflow See other posts from Stack Overflow or by macek
Published on 2010-04-12T21:57:48Z Indexed on 2010/04/12 22:03 UTC
Read the original article Hit count: 129

Filed under:
|
|
|
|

I was helping with an answer in this question and it sparked a question of my own.

  1. Pie is an object that has a pieces array made of of PiePiece objects.
  2. Each PiePiece has a flavor attribute

How do I create a hash that looks like this:

# flavor => number of pieces
{
  :cherry => 3
  :apple => 1
  :strawberry => 2
}

This works, but I think it could be improved

def inventory
  hash = {}
  pieces.each do |p|
    hash[p.flavor] ||= 0
    hash[p.flavor] += 1
  end
  hash
end

Any ideas?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about best-practices