我有 3 个简单的类 CashRegister、Bill 和 Position。CashRegister 由 Bill 对象组成,Bill 对象由 Position 对象组成。它们的实施如下
class CashRegister
def initialize
@bills = []
end
def product_frequency
#???
end
def << bill
@bills << bill
self
end
end
class Bill
attr_reader :positions,:nr
protected :positions
def initialize(nr)
@nr = nr
@positions = []
end
def << pos
@positions << pos
self
end
end
class Position
attr_reader :product,:quantity,:price
def initialize(product,quantity,single_price)
@product = product
@quantity = quantity
@price = single_price * quantity
end
end
我想编写一个product_frequency方法来计算在 CashRegister 中购买产品的频率。此方法返回一个哈希作为结果,其中产品作为键,频率作为值。一个例子是:
pos1 = Position.new('Chicken', 5, 12)
pos2 = Position.new('Soup', 6, 24)
pos3 = Position.new('Burger', 3, 19)
pos4 = Position.new('Chicken', 2, 12)
pos5 = Position.new('Soup', 8, 24)
pos6 = Position.new('Burger', 9, 19)
bill1 = Bill.new(1) << pos1 << pos2 << pos3 #Chicken: 5;Soup: 6;Burger: 3
bill2 = Bill.new(2) << pos4 << pos3 << pos2 #Chicken: 2;Soup: 6;Burger: 3
bill3 = Bill.new(3) << pos6 << pos6 << pos6 #Chicken: 0;Soup: 0;Burger: 27
bill4 = Bill.new(4) << pos4 << pos5 << pos4 #Chicken: 4;Soup: 8;Burger: 0
my_cash_register = CashRegister.new << bill1 << bill2 << bill3 << bill4
my_cash_register.product_frequency #{'Chicken' => 11, 'Soup' => 20, 'Burger' => 33}
我怎样才能达到这个结果?