简体   繁体   中英

Ruby: sum the outputs of .each iteration

I am working on a Ruby project to make a road trip calculator. 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.

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). 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). 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. 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. Here is an example that does the same as 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 .

Check out the documentation for the Enumerable module for more helpful methods that work on arrays and hashes.

You should use map and sum

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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