问题描述
我想创建一个对象,比如说一个Pie.
I want to create an object, let's say a Pie.
class Pie
def initialize(name, flavor)
@name = name
@flavor = flavor
end
end
但是一个Pie可以分为8个部分,一半或一个完整的Pie.为了争辩,我想知道如何给每个Pie对象一个1/8、1/4或整体的价格.我可以这样做:
But a Pie can be divided in 8 pieces, a half or just a whole Pie. For the sake of argument, I would like to know how I could give each Pie object a price per 1/8, 1/4 or per whole. I could do this by doing:
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
但是现在,如果我要创建15个Pie对象,并且可以使用
But now, if I would create fifteen Pie objects, and I would take out randomly some pieces somewhere by using a method such as
getPieceOfPie(pie_name)
我如何能够生成所有完整的可用馅饼和其余碎片的价值?最终使用以下方法:
How would I be able to generate the value of all the available pies that are whole and the remaining pieces? Eventually using a method such as:
myCurrentInventoryHas(pie_name)
# output: 2 whole strawberry pies and 7 pieces.
我知道,我是Ruby nuby.感谢您的回答,评论和帮助!
I know, I am a Ruby nuby. Thank you for your answers, comments and help!
推荐答案
您肯定需要单独的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
这篇关于Ruby编程技术:简单但不是那么简单的对象操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!