我希望能够初始化一个新的 Car 对象并在参数中将一个 Person 对象传递给它,这样它就可以保存在那个 Person 的 @cars 数组中。目前,我采用这种方法:
person = Person.new("Michael")
car = Car.new("Honda", "Accord")
person.add_car(car)
person.add_car(Car.new("Ford", "Taurus"))
person.add_car(Car.new("Toyota", "Prius"))
person.display
但是,我希望能够创建一个新的汽车实例并将它传递给我希望与之关联的 Person 对象。例如:
person = Person.new("Michael")
Car.new("Honda", "Accord", person)
Car.new("Toyota", "Camry", person)
Car.new("Chevy", "Tahoe", person)
person.display
这可能吗?
class Person
attr_accessor :name
def initialize(name)
super
@name = name
@cars = []
end
def display
puts "#{@name} has #{@cars.length} cars"
puts "----------------------------"
@cars.each do |car|
puts "#{car.make} #{car.model}"
end
end
def add_car(car)
@cars.push(car)
end
end
class Car
attr_accessor :make, :model
def initialize(make, model)
@model = model
@make = make
end
def display
puts "#{@make} #{@model}"
end
end
是的,这是可能的,Car#initialize
可以在其参数上调用方法:
class Car
def initialize(make, model, person = nil)
@model = model
@make = make
person.add_car(self) if(person)
end
#...
end
我是一名优秀的程序员,十分优秀!