Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum array of numbers in Ruby?

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.

like image 936
brainfck Avatar asked Oct 08 '09 16:10

brainfck


People also ask

How do you sum a list in Ruby?

The sum() of enumerable is an inbuilt method in Ruby returns the sum of all the elements in the enumerable. If a block is given, the block is applied to the enumerable, then the sum is computed. If the enumerable is empty, it returns init. Parameters: The function accepts a block.

How do you count the number of numbers in an array in Ruby?

Ruby | Array count() operationArray#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.

What does .first do in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


1 Answers

For ruby >= 2.4 you can use sum:

array.sum

For ruby < 2.4 you can use inject:

array.inject(0, :+) 

Note: the 0 base case is needed otherwise nil will be returned on empty arrays:

> [].inject(:+) nil > [].inject(0, :+) 0 
like image 180
jomey Avatar answered Sep 20 '22 01:09

jomey