初始化Ruby代码错误

时间:2016-06-28 12:25:24

标签: ruby-on-rails ruby

我尝试运行这些代码:

class Dog    
   def set_name(name)
      @dogname = name
   end

   def get_name
      return @dogname
   end

   def talk
      return "awww"
   end

   def initialize(title, description)
      @title = title
      @description = description
   end    
end

doggy = Dog.new
doggy.set_name('Sam')
puts doggy.get_name
puts doggy.talk


bogart = Dog.new('The Book', 'The road not taken')
puts bogart.to_s
puts bogart.inspect

我确实确保每个论点都是正确的。但是,我遇到了以下错误。

C:\Ruby200\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) C:/Users/Todd/RubymineProjects/untitled1/test.rb
C:/Users/Todd/RubymineProjects/untitled1/test.rb:15:in `initialize': wrong number of arguments (0 for 2) (ArgumentError)
    from C:/Users/Todd/RubymineProjects/untitled1/test.rb:22:in `new'
    from C:/Users/Todd/RubymineProjects/untitled1/test.rb:22:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'

Process finished with exit code 1

尽我所能找不到问题。知道我想念的地方吗?

5 个答案:

答案 0 :(得分:1)

对象创建 - 您缺少传递给initialize方法的参数。

doggy = Dog.new 应为 doggy = Dog.new('argument1', 'argument2')

答案 1 :(得分:1)

Dog类中,您用两个参数覆盖了构造函数initialize。因此,当您想要为该类创建实例时,您必须为此传递2个参数。 这里doggy = Dog.new你正在尝试创建没有任何参数的实例。所以initialize方法会产生错误。

答案 2 :(得分:1)

在代码中查看此行:

doggy = Dog.new

这里你没有传递参数标题,导致错误的描述。

在创建Dog类的对象时更改一些参数或更改初始化方法,如下所示:

  def initialize(title=nil, description=nil)
    @title = title
    @description = description
  end

答案 3 :(得分:1)

class Dog

  def set_name(name)
    @dogname = name
  end

  def get_name
    return @dogname
  end

  def talk
    return "awww"
  end

  def initialize(title, description)
    @title = title
    @description = description
  end

end

#That will cause an error because your new method have two arguments.
doggy = Dog.new



bogart = Dog.new('The Book', 'The road not taken')
bogart.set_name('Sam')
puts bogart.get_name
puts bogart.talk
puts bogart.to_s
puts bogart.inspect

答案 4 :(得分:1)

您可以更加清楚地阅读错误代码。这一行

  

`initialize&#39;:参数数量错误(0表示2)(ArgumentError)

告诉您ArgumentError的原因。

您将0个参数传递给Dog initialize中的class方法,此方法需要2个参数。

Dog.new # 0 arguments

# your method in Dog class
def initialize(title, description)
  @title = title
  @description = description
end

如果需要发送nil个参数,则必须在此变量上定义默认值

def initialize(title = nil, description = nil)
  @title, @description = title, description
end

所以你的代码看起来像这样。

class Dog
  def initialize(title = nil, description = nil)
    @title = title
    @description = description
  end

  def set_name(name)
    @dogname = name
  end

  def get_name
    @dogname
  end

  def talk
    "awww"
  end
end

我希望这会有所帮助

顺便说一句:在这里查看更多可修改的代码Ruby Styleguide