How to sum array of numbers in Ruby?

There are different ways to achieve this:

Imagine that you have:

a = [1, 2, 3]  

Using sum

a.sum  

Using inject

a.inject(0) { |sum, x| sum + x }  

or

a.inject(:+)  

Using reduce

a.reduce(:+)  

This the Output:

=> 6

That's all folks!

Follow me on twitter

Victor Velazquez

Coder, Musician, Startups, Passionate Dancer & Life Lover. Software Engineer at MagmaLabs, Co-founder of Web Dev Talks, Co-founder of Voltaire, Co-founder of Paqkit, Ex-co-founder of Zaznova.

Subscribe to The zazvick's blog

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!