数组 Ruby 中实例变量的总和

Sum of instance variables in Array Ruby

我有一个数组 item_list = [item1, item2, item3,] 存储有价格的对象。 我想计算这些价格的总和并将其显示为总计。

我试过这样做:

print "Items:"
item_list.each do |item|
  print " #{item.name},"
  prices_arr = []
  prices_arr << item.price
  sum = prices_arr.sum
end
  puts "Total: #{sum}"

但我收到错误消息,未定义的局部变量或方法“sum”。 如果我将 "Total: #{sum}" 放入循环中,它将给我每个项目及其价格,但不是总计。 有什么想法吗?

尝试

sum = item_list.map(&:price).sum

您的方法的问题是变量 sum 是在循环内定义的,这就是为什么它的范围被限制在

内的原因
print "Items:"
item_list.each do |item|
  print " #{item.name},"
  prices_arr = []
  prices_arr << item.price
  sum = prices_arr.sum
end
puts "Total: #{sum}"

所以,更好的方法是:-

sum = 0
print "Items:"
item_list.each do |item|
  print " #{item.name},"
  sum += item.price
end
puts "Total: #{sum}"

这是使用注入之类的工具的绝佳机会。从总和 0 开始,您可以执行以下操作。这使您既可以打印和处理数据项,也可以将它与任意累加器(在本例中是一个从 0 开始的整数)结合起来。

print "Items:"
sum = item_list.inject(0) do |sum, item|
  print " #{item.name},"
  sum += item.price
end
puts "Total: #{sum}"

让我们首先创建一个示例数组item_list

class List
  attr_reader :name, :price
  def initialize(name, price)
    @name, @price = name, price
  end
end

item_list = [List.new("tools", 148.16), List.new("food", 265.13),
             List.new("hair", 84.51), List.new("books", 285.01)]
  #=> [#<List:0x000000019043a8 @name="tools", @price=148.16>,
  #    #<List:0x000000019042e0 @name="food", @price=265.13>,
  #    #<List:0x00000001904268 @name="hair", @price=84.51>,
  #    #<List:0x000000019041a0 @name="books", @price=285.01>]

我们现在可以打印所需的值。

print "Items:"
puts " Total: %.2f" % item_list.sum do |item|
  print " #{item.name},"
  item.price
end
  # tools, food, hair, books, Total: 782.81