在ruby中初始化方法参数问题

时间:2016-10-03 15:17:55

标签: ruby

"在我的示例中,initialize方法期望接收两个参数。将参数与initialize方法关联后,就不能将其关闭。如果这样做,就会产生错误。" - 对于理论来说太多了,但就我而言,情况正好相反;(

    class Player
      attr_accessor :name, :age, :score

      def inicialize(name, age, score)
        @name = name
        @age = age
        @score = score
      end

      def to_s
        "Player #{name} is #{age} old and have #{score} points"
      end
    end

所以我简单地称之为:

player = Player.new("Name", "Surname", 25)

但编译器回复:

`initialize': wrong number of arguments (given 3, expected 0) (ArgumentError)

所以,比我做的那样:

player = Player.new; player.name = 'Peter'

它有效......为什么? 当我删除inicialize的论点时,它就是同一个故事。

1 个答案:

答案 0 :(得分:0)

应该是initialize,而不是inicialize

class Player
  attr_accessor :name, :age, :score

  def initialize(name, age, score)
    @name = name
    @age = age
    @score = score
  end

  def to_s
    "Player #{name} is #{age} old and have #{score} points"
  end
end

player = Player.new("Name", "Surname", 25)
#=> #<Player:0x007fca2a4dfbb0 @age="Surname", @name="Name", @score=25>