I'm attempting to sum only the integers in an array that is passed to my function but keep running up against errors. This is what I have right now.
def sum(*x)
x.each { |i|
unless i.is_a? Integer
x.delete_at(x.index(i))
end
}
x.inject(:+)
end
I don't know the numbers of items that might be in the array as you can see the splat operator. I then loop through each array item and check if it's an integer. If it isn't, it is deleted. Finally after only integers are left, the array is summed.
However, I keep getting the following error.
No implicit conversion of Fixnum into String (TypeError)
(This error references the line inject is on. Any idea what I'm doing wrong here?
x.reduce { |t,e| t+e.to_i }. Add arrays and hashes (and maybe some other objects) and this would work:x.reduce { |t,e| t+e.to_s.to_i }x->xs.