refactoring ruby method
this is a simple question...
Does this method can be refactored?
def sum
total = 0
[1,2,3,4].each do |num|
total += num
end
total
end
开发者_运维知识库
thanks for your help!
You can use this:
[1,2,3,4].inject(0, :+) # => 10
[1,2,3,4].inject { |total,num| total= total+num }
OR as per suggestion below it should be
[1,2,3,4].inject(0) { |total,num| total+num }
>> [1, 2, 3, 4].inject(0) { |acc, x| acc + x }
=> 10
Or simply:
>> [1, 2, 3, 4].inject(0, :+)
=> 10
Same as the following How to sum array of numbers in Ruby?
精彩评论