Ruby Programming Techniques:简单但不那么简单的对象操作

Shy*_*yam 5 ruby math

我想创建一个对象,让我们说一个Pie.

class Pie 
  def initialize(name, flavor) 
    @name = name 
    @flavor = flavor 
  end 
end
Run Code Online (Sandbox Code Playgroud)

但馅饼可分为8个,半个或整个馅饼.为了争论,我想知道如何为每个Pie对象提供每1/8,1/4或每个整体的价格.我可以这样做:

class Pie 
  def initialize(name, flavor, price_all, price_half, price_piece) 
    @name = name 
    @flavor = flavor 
    @price_all = price_all
    @price_half = price_half
    @price_piece = price_piece
  end 
end 
Run Code Online (Sandbox Code Playgroud)

但是现在,如果我要创建十五个Pie对象,我会通过使用诸如此类的方法随机取出某些部分

getPieceOfPie(pie_name)
Run Code Online (Sandbox Code Playgroud)

我如何能够生成所有可用馅饼的价值,以及剩余的碎片?最终使用如下方法:

   myCurrentInventoryHas(pie_name)
   # output: 2 whole strawberry pies and 7 pieces.
Run Code Online (Sandbox Code Playgroud)

我知道,我是一个Ruby nuby.感谢您的回答,评论和帮助!

mač*_*ček 2

你肯定会想要单独Pie上课PiePiece

class Pie
  attr_accessor :pieces
  def initialize
    self.pieces = []
  end

  def add_piece(flavor)
    raise "Pie cannot have more than 8 pieces!" if pieces.count == 8
    self.pieces << PiePiece.new(flavor)
  end

  # a ruby genius could probably write this better... chime in if you can help
  def inventory
    Hash[pieces.group_by(&:flavor).map{|f,p| [f, p.size]}]
  end

end

class PiePiece
  attr_accessor :flavor
  def initialize(flavor)
    self.flavor = flavor
  end
end
Run Code Online (Sandbox Code Playgroud)

示例代码

p = Pie.new
p.add_piece(:strawberry)
p.add_piece(:strawberry)
p.add_piece(:apple)
p.add_piece(:cherry)
p.add_piece(:cherry)
p.add_piece(:cherry)

p.inventory.each_pair do |flavor, count|
  puts "Pieces of #{flavor}: #{count}"
end

# output
# Pieces of strawberry: 2
# Pieces of apple: 1
# Pieces of cherry: 3
Run Code Online (Sandbox Code Playgroud)