Ruby wrong number of arguments

1.8k Views Asked by At

I'm trying to to create my getters and setters using attr_accessor. I want to assign a value to my variables.

Here is my code:

class Person
  def initialize(name)
    attr_accessor :name
  end

  def initialize(age)
    attr_accessor :age
  end
end

person1 = Person.new
person1.name = "Andre"
person1.age  = 22

I get some trouble though. My error is:

q5.rb:6:in `initialize': wrong number of arguments (given 0, expected 1) (ArgumentError)
1

There are 1 best solutions below

5
Tom Lord On BEST ANSWER

This is what you're trying to do:

class Person 
  attr_accessor :name, :age
end

person1 = Person.new
person1.name = "Andre"
person1.age  = 22

An alternative approach, for example, could be:

class Person 
  attr_accessor :name, :age

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

person1 = Person.new("Andre", 22)

The error you're seeing is because you defined (and then re-defined) an initialize method that is expecting one parameter:

def initialize(name)

and then tried to create an object without supplying a parameter:

person1 = Person.new