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

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

class Pie def initialize(name, flavor) @name = name @flavor = flavor end end 

但馅饼可分为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 

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

 getPieceOfPie(pie_name) 

我怎样才能生成所有可用馅饼的价值? 最终使用如下方法:

  myCurrentInventoryHas(pie_name) # output: 2 whole strawberry pies and 7 pieces. 

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

你肯定想要单独的PiePiePiece

 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 

示例代码

 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 

你能创建一个PieSlice对象,每个Pie都有一个PieSlices数组吗?

Pie类可以有一个计数器来指示它的剩余部分。 getPieceOfPie方法将修改此计数器。 然后myCurrentInventoryHas方法可以查看每个Pie,看看有多少Pie正在检查计数器。

一块馅饼不是馅饼。

(用oo术语来说,一个对象应该有明确的责任,使一个对象成为一个馅饼而一个切片可能不是一个明确的责任分配)。