2

Please help, I am a Ruby student, I know how to do the .sum method but not this: how do you define a sum function for an array so that providing any elements will result in the sum of them. The format should be sum([array inputs]) return sum of array elements. For ex: sum([ ]) should return 0, sum([1,2,3]) returns 6 (#again, not [1,2,3].sum). I am so stuck in the box, thank you very much for any help.

2
  • Look for the source of Array#sum :) Commented Jun 6, 2013 at 8:33
  • What sum method do you know? Are you mentioning Rails? Commented Jun 6, 2013 at 9:01

4 Answers 4

3

Solution with usage of Enumerable#inject:

def sum(array)
  array.inject(0){|sum, el| sum + el}
end

Or, as suggested, shorter and more elegant form:

def sum(array)
  array.inject(0, :+)
end
Sign up to request clarification or add additional context in comments.

1 Comment

or array.sum -- see answer from NikDP
2

Use array sum method.

arr = [1,2,3]
arr.sum


def sum(arr)
  arr.sum
end

Comments

1

This will do:

def sum(array)
  array.reduce(0, :+)
end

2 Comments

Actually, you don't need 0. You can do array.reduce(:+).
@sawa [].reduce(:+) # => nil
0
def sum(arr)
 sum = 0
 arr.each{|element| sum=sum+element }
 return sum
end

2 Comments

While this works, so imperative a way of doing thing is not idiomatic in Ruby (and that return is definitely not idiomatic).
Thank you very much, this is more of my level :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.