THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorials explains about how to do sum of array numbers in Ruby?
There are number of ways we can calculate sum of array of numbers in Ruby
sum method: sum method
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
numbers = [1,2,3,4,5]
result=numbers.reduce(0, :+)
puts "#{result}"
result1=numbers.reduce(:+)
puts "#{result1}"
Output
10
numbers = [1,2,3,4,5]
result=numbers.inject(0, :+)
puts "#{result}"
result1=numbers.inject(:+)
puts "#{result1}"
🧮 Tags
Recent posts
Three dots in react components with example|Spread operator How to update ReactJS's `create-react-app`? Difference between super and super props in React constructor class? How to check the element index of a list or array in the swift example How to calculate the sum of all numbers or object values in Array swift with exampleRelated posts