0Day Forums
How to sum array of numbers in Ruby? - Printable Version

+- 0Day Forums (https://0day.red)
+-- Forum: Coding (https://0day.red/Forum-Coding)
+--- Forum: Ruby (https://0day.red/Forum-Ruby)
+--- Thread: How to sum array of numbers in Ruby? (/Thread-How-to-sum-array-of-numbers-in-Ruby)

Pages: 1 2


How to sum array of numbers in Ruby? - officiationru - 07-18-2023

I have an array of integers.

For example:

array = [123,321,12389]

Is there any nice way to get the sum of them?

I know, that

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


would work.


RE: How to sum array of numbers in Ruby? - boxfishvhnifhud - 07-18-2023

Alternatively (just for comparison), if you have Rails installed (actually just ActiveSupport):

require 'activesupport'
array.sum




RE: How to sum array of numbers in Ruby? - ob348 - 07-18-2023

ruby 1.8.7 way is the following:

array.inject(0, &:+)


RE: How to sum array of numbers in Ruby? - Liping868219 - 07-18-2023

Also allows for `[1,2].sum{|x| x * 2 } == 6`:

#

[To see links please register here]

class Array
def sum(method = nil, &block)
if block_given?
raise ArgumentError, "You cannot pass a block and a method!" if method
inject(0) { |sum, i| sum + yield(i) }
elsif method
inject(0) { |sum, i| sum + i.send(method) }
else
inject(0) { |sum, i| sum + i }
end
end
end


RE: How to sum array of numbers in Ruby? - steelworker99784 - 07-18-2023

Just for the sake of diversity, you can also do this if your array is not an array of numbers, but rather an array of objects that have properties that are numbers (e.g. amount):

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


RE: How to sum array of numbers in Ruby? - saiger - 07-18-2023

You can also do it in easy way

def sum(numbers)
return 0 if numbers.length < 1
result = 0
numbers.each { |num| result += num }
result
end





RE: How to sum array of numbers in Ruby? - gibus101423 - 07-18-2023

You can use *.map* and *.sum* like:

array.map { |e| e }.sum



RE: How to sum array of numbers in Ruby? - unrepudiable599253 - 07-18-2023

array.reduce(0, :+)

While equivalent to `array.inject(0, :+)`, the term **reduce** is entering a more common vernacular with the rise of [MapReduce programming models][1].

**inject**, **reduce**, **fold**, **accumulate**, and **compress** are all synonymous as a class of [folding functions][2]. I find consistency across your code base most important, but since various communities tend to prefer one word over another, it’s nonetheless useful to know the alternatives.

To emphasize the map-reduce verbiage, here’s a version that is a little bit more forgiving on what ends up in that array.

array.map(&:to_i).reduce(0, :+)

Some additional relevant reading:

-

[To see links please register here]

-

[To see links please register here]

-

[To see links please register here]



[1]:

[To see links please register here]

[2]:

[To see links please register here]




RE: How to sum array of numbers in Ruby? - unelusive423581 - 07-18-2023

Ruby 2.4.0 is released, and it has an [Enumerable#sum][1] method. So you can do

array.sum

Examples from the docs:

{ 1 => 10, 2 => 20 }.sum {|k, v| k * v } #=> 50
(1..10).sum #=> 55
(1..10).sum {|v| v * 2 } #=> 110


[1]:

[To see links please register here]




RE: How to sum array of numbers in Ruby? - bonninesses516252 - 07-18-2023

# New for Ruby 2.4.0

You can use the aptly named method `Enumerable#sum`. It has a lot of advantages over `inject(:+)` but there are some important notes to read at the end as well.

## Examples

### Ranges

(1..100).sum
#=> 5050

### Arrays

[1, 2, 4, 9, 2, 3].sum
#=> 21

[1.9, 6.3, 20.3, 49.2].sum
#=> 77.7

## Important note
This method is not equivalent to `#inject(:+)`. For example

%w(a b c).inject(:+)
#=> "abc"
%w(a b c).sum
#=> TypeError: String can't be coerced into Integer

Also,


(1..1000000000).sum
#=> 500000000500000000 (execution time: less than 1s)
(1..1000000000).inject(:+)
#=> 500000000500000000 (execution time: upwards of a minute)

See [this answer](

[To see links please register here]

) for more information on why `sum` is like this.