Search code examples
rubyattr-accessor

Ruby wrong number of arguments


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)

Solution

  • 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