Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby继承nil类_Ruby - Fatal编程技术网

Ruby继承nil类

Ruby继承nil类,ruby,Ruby,我试图制作一个游戏,但是我在为属性设置默认值和为每个子类设置不同的默认值时遇到了问题 问题是: class Player attr_accessor :hp @hp = 2 end class Harper < Player @hp = 5 end bill = Harper.new.hp #=>nil 我希望Harper.new.hp为5,但它显示为零,我不明白为什么。您需要将赋值放在初始化函数上: class Player attr_accessor

我试图制作一个游戏,但是我在为属性设置默认值和为每个子类设置不同的默认值时遇到了问题

问题是:

class Player
   attr_accessor :hp 
   @hp = 2
end

class Harper < Player
  @hp = 5
end

bill = Harper.new.hp #=>nil

我希望Harper.new.hp为5,但它显示为零,我不明白为什么。

您需要将赋值放在初始化函数上:

class Player
  attr_accessor :hp 
  def initialize
    @hp = 2
  end
end

class Harper < Player
  def initialize
    super  ## May not be necessary for now.
    @hp = 5
  end
end

bill = Harper.new.hp
# => 5
新类方法运行实例方法初始化,因此您的代码应该如下所示:

class Harper < Player
  def initialize
    @hp = 5
  end
end

初始化的问题在于它存在于类级别。也就是说,您正在创建一个类实例变量?不是您期望的对象实例变量

为了创建实例变量,您需要在实例级别运行的方法中执行该操作,就像使用新方法创建对象时运行的initialize方法一样

例如:

class Hello
  @world = "World!"
  def initialize
    @to_be_or_not_to_be = "be!"
  end
end
=> :initialize

inst = Hello.new
inst.instance_variables
=> [:@to_be_or_not_to_be]

Hello.instance_variables
=> [:@world]

inst.class.instance_variables
=> [:@world]

你的问题是什么?