简体   繁体   中英

Loop through an array while summing the output

I am trying to use a for loop and then sum all of the outputs. I know this is a basic question, but I am not sure if I should be trying to solve this within the loop or using another array.

For example:

for i in 1..100
if foo / 2 == 0
#find the sum of all outputs
end

end

Try this:

(2..100).step(2).inject(:+) #=> 2550

Or:

2.step(100,2).inject(:+) #=> 2550

You can use sum instead of inject(:+) from Ruby 2.4+

I'm not entirely sure what you're asking, but my initial understanding is that you want to sum all of the numbers in a range (1..100) that meet a specific condition. In this case, something divided by 2 cannot equal zero aside from zero itself. I'm wondering if you meant %2, in which case, you're asking to sum all the even numbers in the range 1..100. This can be accomplished by doing the following.

    (1..100).select {|x| x if x.even?}.reduce(:+) 

Effectively, you want to enumerate over a range and select only the numbers that meet your condition, as specified in the block. Calling reduce and passing it an accumulator.

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