这是我的表格,如何汇总表格底部的价格和数量字段?
def output_action_header(text)
puts "\n#{text.upcase.center(60)}\n\n"
end
def output_stock_table(stock=[])
print " " + "Stock Type".ljust(30)
print " " + "Number".ljust(20)
print " " + "Transaction".ljust(20)
print " " + "Price".rjust(6) + "\n"
puts "-" * 90
stock.each do |rest|
line = " " << rest.name.titleize.ljust(30)
line << " " + rest.qty.titleize.ljust(20)
line << " " + rest.transaction.titleize.ljust(20)
line << " " + rest.formatted_price.rjust(6)
puts line
end
puts "-" * 90
end
答案 0 :(得分:0)
如果您正在使用Ruby on Rails,例如qty
是一个数字,你可以这样做:
stock.sum(&:qty)
或者如果您使用的是Rails,但qty
不是数字:
stock.sum { |rest| rest.qty.to_i }
如果你不使用Rails,你可以这样做:
stock.inject(0) { |sum, rest| sum + rest.qty }