程式扎記: [ 常見問題 ] How to sum array of numbers in Ruby?

標籤

2014年11月7日 星期五

[ 常見問題 ] How to sum array of numbers in Ruby?

Source From Here
Question
I have an array of integers. For example:
  1. array = [123,321,12389]  
Is there any nice way to get the sum of them? An ugly way is:
  1. sum = 0  
  2. array.each { |a| sum+=a }  
How-To
Array in Ruby include Enumerable module. So you can try inject method:


For example:
>> array = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
>> array.inject(0,:+)
=> 15 # 1+2+3+4+5
>> array.inject(:+)
=> 15
>> array.inject(0){|sum,obj| sum+obj}
=> 15
>> array.inject{|sum,obj| sum+obj}
=> 15


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!