How to do sum of array numbers in Ruby with examples
This tutorial explains how to do the sum of array numbers in Ruby.
- Sum of array numbers
- Sum of numbers between a and b
Ruby sum of array numbers with an example
There are a number of ways we can calculate the sum of an array of numbers in Ruby
- sum method
- reduce method
- inject method
sum method
The sum
method is only available in the Ruby 2.4 version onwards. It returns the sum of all elements. It returns 0 if the array is empty. It added an enumerable type and was used with Arrays.
If the array is a string, It returns by appending all elements.
Here is an example
numbers = [1,2,3,4]
result = numbers.sum
puts "#{result}"
result1=0
numbers.sum {|item| result1+=item }
puts "#{result1}"
result2=numbers.sum {|item| item }
puts "#{result2}"
Output
10
10
10
reduce method
reduce method reduces the array of elements into a single value.
numbers = [1,2,3,4,5]
result=numbers.reduce(0, :+)
puts "#{result}"
result1=numbers.reduce(:+)
puts "#{result1}"
Output
10
inject method
inject
method combine all elements with a given binary operation.
inject and reduce functions behavior are the same. used with the below ruby 2.4 version only.
Here is an example
numbers = [1,2,3,4,5]
result=numbers.inject(0, :+)
puts "#{result}"
result1=numbers.inject(:+)
puts "#{result1}"
Sum of numbers between two numbers in Ruby
For example, Two numbers are 1, 10. This program returns the sum of all numbers from 1 to 10.
def sum(first,second)
first, second = second, first if first > second
return (first..second).sum
end
print sum(1,10)
Output:
55
Conclusion
Learned multiple ways to sum of array numbers, between two numbers in Ruby and rails language.