Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird wrong number of arguments (1 for 0) error?

I'm having an issue with a method definition. I have this code in my "buy" model:

def update_amount newamount
    self.total_amount = self.total_amount +newamount
end

and this code at other place:

buy.update_amount(amount)

If I run the program, I get this error:

ArgumentError (wrong number of arguments (1 for 0)):
  app/models/buy.rb:18:in `update_amount'

Now, if I change for this (just to try):

buy.update_amount

I get this error:

ArgumentError (wrong number of arguments (0 for 1)):
      app/models/buy.rb:18:in `update_amount'

I'm new with Ruby on Rails so it's probably something easy.

like image 415
DemianArdus Avatar asked Dec 01 '22 19:12

DemianArdus


2 Answers

Quite tricky error you have! The line:

self.total_amount = self.total_amount +newamount

Is interpreted by Ruby as:

self.total_amount = self.total_amount(+newamount)

Hence the you get the ArgumentError.

The Ruby lexer mistakes +newamount for a parameter (i.e. a unary plus followed by the newamount identifier) because it knows that total_amount is a method call, and the + is not followed by a space. Writing the line as:

self.total_amount = self.total_amount + newamount

Will fix the problem. Or better, use the += shorthand as @backpackerhh suggested.

like image 144
toro2k Avatar answered Dec 06 '22 15:12

toro2k


def update_amount(newamount)
  self.total_amount += newamount
end

This adds the new amount to the current value of total_amount attribute.

You were trying to pass newamount as an argument to your self.total_amount attribute.

like image 37
backpackerhh Avatar answered Dec 06 '22 15:12

backpackerhh