简体   繁体   English

Ruby:将.each迭代的输出求和

[英]Ruby: sum the outputs of .each iteration

I am working on a Ruby project to make a road trip calculator. 我正在一个Ruby项目中制作旅行计算器。 The program takes the miles per gallon and fuel tank size from multiple users to calculate and compare fuel economy. 该程序从多个用户获取每加仑英里数和油箱尺寸,以计算和比较燃油经济性。 In the following portion of code I want to iterate over an array named vehicles and divide 3000 by the mpg of each element in that array. 在下面的代码部分中,我想遍历一个名为Vehicles的数组,并将3000除以该数组中每个元素的mpg。

I'm struggling with what I want to do next: take those outputs and sum them (3000 / total_fuel[:mpg] + 3000 / total_fuel[:mpg] + 3000 / total_fuel[:mpg] ... of each element). 我正在为下一步工作苦苦挣扎:获取这些输出并求和(每个元素的3000 / total_fuel [:mpg] + 3000 / total_fuel [:mpg] + 3000 / total_fuel [:mpg] ...)。 So far this is what I have: 到目前为止,这就是我所拥有的:

    vehicles.each do |total_fuel|
      total_fuel = (3000 / total_fuel[:mpg])
      print total_fuel
    end

When it prints it just outputs the calculations right next to each other with no spaces (eg 150166). 在打印时,它仅将计算结果彼此紧挨输出,没有空格(例如150166)。 I'm totally lost on how to then take those numbers and add them, especially since it will be a different amount of outputs depending on how many users entered info. 我对如何获取这些数字并将其相加完全迷失了,特别是因为根据输入用户的数量,输出的数量将有所不同。

I hope that was clear. 我希望这很清楚。 Any ideas? 有任何想法吗?

It sounds like what you need is the sum method. 听起来您需要的是sum方法。 In your case, you don't want to just iterate over all vehicles and execute a block, but you want to sum the results of the block and return a single value. 在您的情况下,您不想只遍历所有车辆并执行一个块,而是想对块的结果求和并返回一个值。

 total_fuel = vehicles.sum do |vehicle|
   3000 / vehicle[:mpg]
 end

A closely related and very useful method is reduce , which allows you to specify how exactly multiple values should be reduced into one. 一个紧密相关且非常有用的方法是reduce ,它使您可以指定将多个值精确地减少为一个的方法。 Here is an example that does the same as sum : 这是一个与sum相同的示例:

# Sum some numbers
(5..10).reduce(:+)                             #=> 45

But since you can specify exactly how the values should be combined, the method can be applied in more cases than sum . 但是,由于您可以精确指定值的组合方式,因此该方法可以比sum应用于更多情况。

Check out the documentation for the Enumerable module for more helpful methods that work on arrays and hashes. 请查阅Enumerable模块的文档,以获取适用于数组和哈希的更有用的方法。

You should use map and sum 您应该使用mapsum

total_fuel = vehicles.map { |vehicle| 3000 / vehicle[:mpg] }.sum

or 要么

total_fuel = vehicles.map { |vehicle| 3000 / vehicle[:mpg] }.reduce(:+)
# for Ruby version < 2.4

Just another option using Enumerable#inject : 另一个使用Enumerable#inject的选项:

total_fuel =  = vehicles.inject(0) { |total_fuel, vehicle| total_fuel += 3000.0 / vehicle[:mpg] }

Please, use 3000.0 instead of 3000 , so you get float result. 请使用3000.0而不是3000 ,这样您将获得浮点结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM