我对 Ruby 没什么经验,而且我来自 C++,C++ 中通常使用初始值设定项列表。关于 Ruby,我想了解的一件事如下:
给定以下车辆类及其子类汽车:
class Vehicle
attr_reader :wheels
def initialize(wheels)
@wheels = wheels
end
end
class Car < Vehicle
def initialize(car_stuff)
@wheels = 4 # this is the part I don't like! ;)
@car_stuff = car_stuff
end
end
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以调用超类构造函数方法,而不是遍历该类Vehicle可能具有的不同变量?
先感谢您。
它的用途super是:
class Car < Vehicle
def initialize(car_stuff)
super(4)
@car_stuff = car_stuff
end
end
Run Code Online (Sandbox Code Playgroud)