如何在声明时使用一个键的值作为对 Ruby 中同一散列中另一个键值的操作的一部分?
我的意思是这样的:
purchase = {product: 'phone',
quantity: 5,
price: 120,
total: self.quantity * self.price
}
我认为这会很有用,例如,如果值 quantity
由外部 API 分配,该 API 从中消耗有限的查询,那么如果 total
也请求,一个花费两个查询而不是要求“数量”只花费一个查询。
最佳答案
我建议创建一个执行计算的 Purchase
模型:
class Purchase
attr_reader :product, quantity, price
def initialize(attributes = {})
@product = attributes[:product]
@quantity = attributes[:quantity]
@price = attributes[:price]
end
def total
quantity * price
end
def to_h
{
product: product,
quantity: quantity,
price: price,
total: total
}
end
end
比将您的代码更改为:
purchase = Purchase.new(product: 'phone', quantity: 5, price: 120).to_h
作为奖励:此模型易于理解且易于测试。
关于ruby-on-rails - 使用键的值作为同一散列中另一个键的值的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37282026/