user3685089 user3685089 - 2 months ago 8
Ruby Question

Inicialize method arguments issue

"In my example, the initialize method expects to receive the two arguments. Once you associate an argument with the initialize method, you can not leave it off. If you do, it will generate an error." - so much for the theory but in my case it is the opposite ;(

class Player
attr_accessor :name, :age, :score

def inicialize(name, age, score)
@name = name
@age = age
@score = score
end

def to_s
"Player #{name} is #{age} old and have #{score} points"
end
end


So I call it simply:

player = Player.new("Name", "Surname", 25)


but the compiler responds:

`initialize': wrong number of arguments (given 3, expected 0) (ArgumentError)


So, than I do:

player = Player.new; player.name = 'Peter'


and it works.... why?
When I delete the arguments of inicialize it is the same exact story.

Answer

it should be initialize, not inicialize.

class Player
  attr_accessor :name, :age, :score

  def initialize(name, age, score)
    @name = name
    @age = age
    @score = score
  end

  def to_s
    "Player #{name} is #{age} old and have #{score} points"
  end
end

player = Player.new("Name", "Surname", 25)
#=> #<Player:0x007fca2a4dfbb0 @age="Surname", @name="Name", @score=25>