Calculate the sum of objects for each property of a unique object in Ruby

I helped with an answer in this question and it raised a question of my own.

  • Pie

    is an object that has an array pieces

    of PiePiece

    objects.
  • Everyone PiePiece

    has an attributeflavor

How to create a hash that looks like this:

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

      

It 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?

+2


source to share


1 answer


def inventory
  Hash[pieces.group_by(&:flavor).map{|f,p| [f, p.size]}]
end

      



+5


source







All Articles