1

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!

Amed R
  • 100
  • 8
  • 2
    Questions where you're asking for suggestions to refactor and/or improve existing code are better suited for the new [code review stackexchange site](http://codereview.stackexchange.com) than stackoverflow. Consider asking similar questions there in the future. Thank you. – sepp2k Feb 27 '11 at 18:58

4 Answers4

13

You can use this:

[1,2,3,4].inject(0, :+) # => 10
Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
  • 2
    `[].inject(:+)` will return `nil`. What's wrong with that? Why do we need `0` instead of `nil`? – Vasiliy Ermolovich Feb 27 '11 at 19:02
  • 1
    a) Because it's what the OP code does, b) because the sum of the empty set is 0 according to any definition I've ever read and c) you can't do arithmetic on nil so a return value of nil just isn't useful. – sepp2k Feb 27 '11 at 19:06
  • To elaborate on point c: I would expect something like `balance - sum(items_bought.map(&:price))` to evaluate to `balance` if `items_bought` is empty, not raise an exception. – sepp2k Feb 27 '11 at 19:08
3
[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 }
Deepak N
  • 2,561
  • 2
  • 30
  • 44
  • 3
    The assignment in `a = a+b` is unnecessary and misleading. It should just be `a+b`. Also to be equivalent to his code it should be `inject(0)` (otherwise the result is different for the empty array). – sepp2k Feb 27 '11 at 18:41
  • 2
    Updated the answer as per your suggestions.Thanks!! – Deepak N Feb 27 '11 at 18:47
2
>> [1, 2, 3, 4].inject(0) { |acc, x| acc + x }
=> 10

Or simply:

>> [1, 2, 3, 4].inject(0, :+)
=> 10
tokland
  • 66,169
  • 13
  • 144
  • 170
0

Same as the following How to sum array of numbers in Ruby?

Community
  • 1
  • 1
Steve Wilhelm
  • 6,200
  • 2
  • 32
  • 36