I'm trying to make a game but I am having problems settinga default value for an attribute and having a different default value for each subclass.
Here is the problem:
class Player
attr_accessor :hp
@hp = 2
end
class Harper < Player
@hp = 5
end
bill = Harper.new.hp #=>nil
I'm expecting Harper.new.hp
to be 5
but it's showing nil instead, and I don't understand why.
The problem with your initialization is that it exists at the class level. That is, you are creating a class instance variable (confusing?) not an object-instance variable as you expect.
In order to create an instance variable you need to do it in a method run at the instance level, like the initialize method which runs when you create an object with the "new" method.
Example:
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]
You need to place your assignments on an initialize function:
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
new
class method runs instance method initialize
, so your code should look like:
class Harper < Player
def initialize
@hp = 5
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.