I was helping with an answer in this question and it sparked a question of my own.
- Pieis an object that has a- piecesarray made of of- PiePieceobjects.
- Each PiePiecehas aflavorattribute
How do I create a hash that looks like this:
# flavor => number of pieces
{
  :cherry => 3
  :apple => 1
  :strawberry => 2
}
This works,开发者_StackOverflow中文版 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?
def inventory
  Hash[pieces.group_by(&:flavor).map{|f,p| [f, p.size]}]
end
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论