我最近一直在使用Ruby,但似乎找不到我的问题的答案。
我有一个班级和一个子班级。类具有某种initialize
方法,子类具有其自己的initialize
方法,该方法应该从中继承一些(但不是全部)变量,并将其自身的变量添加到子类对象中。
我Person
有@name
,@age
和@occupation
。
我Viking
是应该有一个@name
和@age
它从继承Person
,另外一个@weapon
它Person
没有。一个Viking
显然不需要任何东西@occupation
,也不应该有一个。
# doesn't work
class Person
def initialize(name, age, occupation)
@name = name
@age = age
@occupation = occupation
end
end
class Viking < Person
def initialize(name, age, weapon)
super(name, age) # this seems to cause error
@weapon = weapon
end
end
eric = Viking.new("Eric", 24, 'broadsword')
# ArgError: …
Run Code Online (Sandbox Code Playgroud) 我有以下代码
class Room
attr_reader :content, :descr
def initialize
@content = get_content
@descr = get_description
end
def get_content
['errors', 'bugs', 'syntax problems'].sample
end
def get_description
"This room has #{self.content}"
end
end
@rooms = Array.new(3, Array.new(3))
@rooms[1][1] ||= Room.new
# => #<Room:0x68985d8 @content="errors", @descr="This room has errors">
p @rooms # =>
#[[nil, #<Room:0x68985d8 @content="errors", @descr="This room has errors">, nil],
# [nil, #<Room:0x68985d8 @content="errors", @descr="This room has errors">, nil],
# [nil, #<Room:0x68985d8 @content="errors", @descr="This room has errors">, nil]]
@rooms = Array.new(3, Array.new(3))
@rooms[1][2] …
Run Code Online (Sandbox Code Playgroud)