Reputation: 21
This is copied from Eloquent Ruby book:
class Document
def words
@content.split
end
def word_count
word.size
end
end
doc = Document.new("Ethics", "Spionza", "By that which is...")
doc.word_count
I get this error:
`initialize': wrong number of arguments (3 for 0) (ArgumentError)
I do not understand why. What's wrong with this example?
Upvotes: 1
Views: 677
Reputation: 36860
As has been mentioned, you need to define an initialize method.
In Ruby, the initialize method is an instance method called automatically when you use the .new
class method, and the class method arguments are passed to the instance method.
You have three arguments: "Ethics", "Spionza" and ""By that which is..."
So because there's no #initialize
method, the Ruby default is used, which expects no arguments but you're passing three.
(and you misspelled "Spinoza" :) )
In your use case it should probably look like this.
class Document
def initialize(category, author, content)
@category = category
@author = author
@content = content
end
def words
@content.split
end
def word_count
words.size
end
end
doc = Document.new("Ethics", "Spionza", "By that which is...")
doc.word_count
Upvotes: 2
Reputation: 5273
As @fiskeben points out, you need to define an initialize
method and specify the appropriate arguments. The example below accepts 2 arguments, which are set as instance variables.
Note that the method body of the word_count
method has been changed to access the @content
instance variable (since it's not clear where the word
variable in word.size
is defined).
class Document
def initialize(name, content)
@name = name
@content = content
end
def words
@content.split
end
def word_count
@content.size
end
end
doc = Document.new("Book Name", "Book Content")
puts doc.word_count
Upvotes: 0
Reputation: 3467
You haven't specified a constructor (def initialize
) and the default constructor only takes zero arguments.
Add the initialize
method to your class.
Upvotes: 1