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。 感谢您的回答,评论和帮助!
你肯定想要单独的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
示例代码
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术语来说,一个对象应该有明确的责任,使一个对象成为一个馅饼而一个切片可能不是一个明确的责任分配)。
- Heroku rails 3.1 app – 在本地编译资产与在slug编译期间编译资产
- 将JSON响应从Ruby映射到Python
- 使用动态变量渲染部分rails
- “未定义的方法’组’用于Rails:模块”在Mac上运行“rails generate rspec:install”时
- ActiveAdmin Access过滤集合
- gem没有在Heroku上卸载
- 用户的Rails模型结构
- 无法在Yosemite DP 7上安装Cocoapods
- rails生成rspec:install config / environments / development.rb:1:在`’:undefined method`configure’