Can we get the sum of the whole array without using the ear?

Asked 1 years ago, Updated 1 years ago, 123 views

array = [123,321,12389]

You want to find the total sum of the arrays in an array that stores these integers.

Is there any other function like sum() other than adding it directly using each?

sum = 0
array.each { |a| sum+=a }
would work.

array math ruby

2022-09-22 13:01

1 Answers

The simplest way is

array.inject(0, :+)

There is. Where 0 is written to return 0 instead of nil if x is an empty array.

> [].inject(:+)
nil
> [].inject(0, :+)
0

If Ruby is less than 1.8

array.inject(0){|sum,x| sum + x }

You can replace it with .


2022-09-22 13:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.