Accidental submit..

As I started.. use Inject

def sum (*numbers)
   numbers.inject {|sum, n| sum + n }
end

Inject initialises an empty (zero) receptacle for aggregated data for you.

More at http://blog.jayfields.com/2008/03/ruby-inject.html

On Thu, Nov 20, 2014 at 9:38 AM, Roelof Wobben <r.wobben / home.nl> wrote:

>  Thanks,
>
> That is solved,
> But now I have this test :
>
> Test.assert_equals(6, sum (1,2,3) )
>
> And I see this error :
>
> -e:10: syntax error, unexpected ( arg, expecting keyword_do or '{' or '('
> Test.assert_equals(6, sum (1,2,3) )
>
> Roelof
>
> Jeremy Axelrod schreef op 20-11-2014 8:31:
>
> The 'sum' variable needs to be initialized or else it takes the value of
> nil. So in the line 'sum += n', sum is nil. You can solve this by setting
> sum = 0 at the beginning of the method.
>
> On Wed, Nov 19, 2014 at 11:22 PM, Roelof Wobben <r.wobben / home.nl> wrote:
>
>>  Hello,
>>
>> I have a method that takes a unlimited number of integers and adds them
>> all together .
>>
>> So I did this :
>>
>> def sum (*numbers)
>>    numbers.each do |n|
>>       sum += n if n.is_a? Integer
>>    end
>> end
>>
>> but when I run it I see this error message :
>>
>> `block in sum': undefined method `+' for nil:NilClass (NoMethodError)
>> 	from `each'
>> 	from  `sum'
>> 	from  `
>>
>> '
>> why do I get a nilClass there. As far as I know this is a normal way to
>> add things up.
>>
>> Roelof
>>
>>
>>
>
>


-- 
-- 
*Augusts Bautra*


*Creative MobileKronvalda bulvaris 10, Riga**office: 00371 67227747*
*mobile: 00371 29957771*
*www.creo.mobi <http://www.creo.mobi/>*