这是从 Eloquent Ruby 一书中复制的:
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
我收到这个错误:
`initialize': wrong number of arguments (3 for 0) (ArgumentError)
我不明白为什么。这个例子有什么问题?
最佳答案
如前所述,您需要定义一个初始化方法。
在Ruby 中,initialize 方法是在使用.new
类方法时自动调用的实例方法,类方法参数传递给实例方法。
你有三个论点:“伦理学”、“Spionza”和““By that what is...”
因为没有 #initialize
方法,所以使用 Ruby 默认值,它不需要参数,但你传递了三个。
(你拼错了“Spinoza”:))
在您的用例中,它可能看起来像这样。
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
关于ruby - 为什么会出现参数错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43836438/