Take the 2-minute tour ×

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

Any ideas?

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted
def inventory
  Hash[pieces.group_by(&:flavor).map{|f,p| [f, p.size]}]
share|improve this answer
Nice. Never even knew group_by existed. –  bergyman Apr 12 '10 at 22:18
It's new to Ruby 1.8.7. Just require "backports" if using 1.8.6. BTW, Hash[key_value_pairs] is also new to 1.8.7 –  Marc-André Lafortune Apr 12 '10 at 22:42
Using Ruby 1.9, thanks :) –  maček Apr 13 '10 at 3:29
add comment

Your Answer


