{

How to Generate Random number in Ruby with examples


This tutorials explains about how to do sum of array numbers in Ruby?

Ruby sum of array numbers

There are number of ways we can calculate sum of array of numbers in Ruby

  • sum method
  • reduce method
  • inject method

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}"
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.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.