
-----------------------------------
Clayton
Fri Oct 27, 2006 7:26 pm

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:


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.)

-----------------------------------
wtd
Fri Oct 27, 2006 9:55 pm


-----------------------------------
In your function, "integers" is an Array.

When you use "each" it passes each element of the Array to the block in turn.

def sum(*integers)
   total = 0
   integers.each { |integer| total += integer }
   total
end

But then, you really should...

class Array
   def sum
      inject(0) { |a, b| a + b }
   end
end

[1, 2, 3, 4].sum # => 10
