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


沒有留言:

張貼留言

[ Python 常見問題 ] python generator “send” function purpose?

Source From  Here   Question   Can someone give me an example of why the "send" function associated with Python generator function...