Getting `initialize': wrong number of arguments(1 for 0) (ArgumentError) for simple ruby app
Asked Answered
D

4

14

This is my first ruby app. And I am a stack overflow virgin... When I run the following program:

class NameApp

def intialize(name)
    @names = []
end

def name_question
    print "What is your name? "
    answer = gets.chomp
    @names += answer.to_s
    puts "The number of characters in your name is " + names.length
end


def name_length
    if @names.length > 25 then 
        print "Your name is longer than 25 characters."
    else 
        print "Your name is too short."
    end
end

end

name_app = NameApp.new("Test1")
name_app.class # => NameApp

name_app.name_question
name_app.name_length

I get this simple error message result:

name.rb:26:in `initialize': wrong number of arguments(1 for 0) (ArgumentError)
from nameapp.rb:26:in `new'
from nameapp.rb:26:in `<main>'

Can you help me trouble shoot?

Denunciatory answered 8/9, 2013 at 2:18 Comment(0)
D
9

Since you have not defined the method initialize for NameApp, by default, it takes zero arguments, but you passed one argument "Test1" via the constructor new.

Distraction answered 8/9, 2013 at 2:23 Comment(3)
Answer below regarding initialize being misspelt is more useful.Servais
@RyanSandridge Why? That answer is just based on a guess.Distraction
It isn't based on a guess. The code sample clearly shows that initialize was misspelled as intialize. Your answer is correct, that the method initialize was not defined; however pointing out that it was simply a spelling mistake is more useful.Servais
P
71

You spelled "initialize" wrong. I did that a few times too when I was starting out, and that was hard to debug. Why ruby didn't name it "init", I'll never know.

Pergola answered 8/9, 2013 at 7:11 Comment(0)
D
9

Since you have not defined the method initialize for NameApp, by default, it takes zero arguments, but you passed one argument "Test1" via the constructor new.

Distraction answered 8/9, 2013 at 2:23 Comment(3)
Answer below regarding initialize being misspelt is more useful.Servais
@RyanSandridge Why? That answer is just based on a guess.Distraction
It isn't based on a guess. The code sample clearly shows that initialize was misspelled as intialize. Your answer is correct, that the method initialize was not defined; however pointing out that it was simply a spelling mistake is more useful.Servais
E
1

If you're reading this thread and you spelled initialize correctly the issue might be related to your super call.

This fails:

def initialize(bar:)
  super
  @bar = bar
end

And this works:

def initialize(bar:)
  super()
  @bar = bar
end
Economizer answered 13/10, 2022 at 18:4 Comment(0)
N
0

For require_relative 'user' move old 'user.rb' up one level rename 'user2.rb' to 'user.rb'. Also, there is a typo.

Newlin answered 10/11, 2018 at 21:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.