{

How to do sum of array numbers 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.





Related posts

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

How to remove an element from an array in Ruby Programming| Ruby on Rails by Example

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to print the name of a Ruby class| Ruby on Rails By Example

How to check if the variable is defined in Ruby with examples

How to Find the minimum and maximum values in an array and hash Ruby with examples

How to Generate Random number in Ruby with examples