开发者

refactoring ruby method

开发者 https://www.devze.com 2023-02-13 14:03 出处:网络
this is a simple question... Does this method can be refactored? def sum total = 0 [1,2,3,4].each do |num|

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消