微信搜索“毛凌志岗前心得”小程序
I have an array of integers.
For example:
array = [123,321,12389]
Is there any nice way to get the sum of them?
I know, that
sum = 0array.each { |a| sum+=a }
would work.
offer of my own reputation for an answer to this question
Try this:
array.inject{|sum,x| sum + x }
Documentation
array.inject(:+)
Add sum to the Array class
class Array def sum self.inject{|sum,x| sum + x } endend
Then do fun stuff like:
[1,2,3,4].sum
Alternatively (just for comparison), if you have Rails installed (actually just ActiveSupport):
require 'activesupport'array.sum
Or try the ruby 1.9 way
Copyright @ 2024 lexus Powered by .NET 8.0 on Kubernetes Powered by: .Text and ASP.NET Theme by: .NET Monster