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!
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
[].inject(:+) will return nil. What's wrong with that? Why do we need 0 instead of nil?balance - sum(items_bought.map(&:price)) to evaluate to balance if items_bought is empty, not raise an exception.[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 }