Computer Science Canada

Array trouble

Author:  Clayton [ Fri Oct 27, 2006 7:26 pm ]
Post subject:  Array trouble

i have a function called add, and from wtd's tutorial, it should be able to take any number of integers and form them into an array, however, it doesnt seem to be working right. my code:

Ruby:

def add(*integers)
        total = 0
        integers.each do |array_element|
                total += integers(array_element)
        end
        return total
end

puts "#{add(1,2,3,4,5,6,7,8,9)}"


I keep getting an error on line 3 and I don't know why (I think it has something to do with "integers" but i dont know for sure.)

Author:  wtd [ Fri Oct 27, 2006 9:55 pm ]
Post subject: 

In your function, "integers" is an Array.

When you use "each" it passes each element of the Array to the block in turn.

code:
def sum(*integers)
   total = 0
   integers.each { |integer| total += integer }
   total
end


But then, you really should...

code:
class Array
   def sum
      inject(0) { |a, b| a + b }
   end
end


code:
[1, 2, 3, 4].sum # => 10


: