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!

1
  • 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 than stackoverflow. Consider asking similar questions there in the future. Thank you. Commented Feb 27, 2011 at 18:58

4 Answers 4

13

You can use this:

[1,2,3,4].inject(0, :+) # => 10
Sign up to request clarification or add additional context in comments.

3 Comments

[].inject(:+) will return nil. What's wrong with that? Why do we need 0 instead of nil?
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.
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.
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 }

2 Comments

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).
Updated the answer as per your suggestions.Thanks!!
2
>> [1, 2, 3, 4].inject(0) { |acc, x| acc + x }
=> 10

Or simply:

>> [1, 2, 3, 4].inject(0, :+)
=> 10

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.