ruby - 为什么会出现参数错误?

标签 ruby

这是从 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/

相关文章:

ruby - 建筑 gem - InvalidSpecificationException [...] 不是文件

ruby-on-rails - Ruby:什么会导致同一代码块的执行在一遍又一遍地运行时随着时间的推移而变慢?

ruby - 使用 Watir 自动进行身份验证

Ruby - Expect 和 Pty 的问题

ruby - 为什么日期解析取决于分隔符?

ruby - 为什么我会在最新版本的 RVM 中看到这条正在运行的 after_cd 消息?

ruby-on-rails - Ruby on Rails 中的 FullCalendar 无法正常工作

ruby-on-rails - Rspec 不显示颜色

ruby - 我如何停止特定的 ruby 守护进程?

ruby-on-rails - 如何检查数组中的每个单词是否包含子字符串并拒绝 Ruby on Rails 中的子字符串?