For ruby >= 2.4 you can use sum:
array.sum
For ruby < 2.4 you can use inject:
array.inject(0, :+)
Note: the 0
base case is needed otherwise nil
will be returned on empty arrays:
> [].inject(:+)
nil
> [].inject(0, :+)
0
More Related Contents:
- Very Basic Ruby puts and gets
- How do I pick randomly from an array?
- How to check if a value exists in an array in Ruby
- How to select unique elements
- Ruby array access 2 consecutive(chained) elements at a time
- How to find and return a duplicate value in array
- Array#each vs. Array#map
- What does %w(array) mean?
- How to split (chunk) a Ruby array into parts of X elements? [duplicate]
- How to find an item in array which has the most occurrences [duplicate]
- How to count duplicate elements in a Ruby array
- Creating matrix with `Array.new(n, Array.new)`
- Create two-dimensional arrays and access sub-arrays in Ruby
- How do I search within an array of hashes by hash values in ruby?
- What is the best way to convert an array to a hash in Ruby
- Find key/value pairs deep inside a hash containing an arbitrary number of nested hashes and arrays
- Ruby method Array#
- Need to split arrays to sub arrays of specified size in Ruby [duplicate]
- How to chunk an array in Ruby
- Ruby – Difference between Array#
- Sort an array according to the elements of another array
- Convert array of 2-element arrays into a hash, where duplicate keys append additional values
- How to sort an array in Ruby to a particular order?
- How do you add an array to another array in Ruby and not end up with a multi-dimensional result?
- How to count identical string elements in a Ruby array
- Ruby array subtraction without removing items more than once
- Where is it legal to use ruby splat operator?
- Round up to the nearest tenth?
- How do I remove blank elements from an array?
- All factors of a given number