这是我到目前为止所做的,但如果用户输入2种或更多车型,则数组不会保存第一个值。如果我删除car.get_方法,程序运行正常而不保存用户输入。有没有我缺少的方法?
class Cars
def set_make(make)
end
def set_model(model)
end
def set_year(year)
end
array_of_cars = Array.new
print "How many cars do you want to create? "
num_cars = gets.to_i
puts
for i in 1.. num_cars
puts
print "Enter make for car #{i}: "
make = gets.chomp
print "Enter model for car #{i}: "
model = gets.chomp
print "Enter year of car #{i}: "
year = gets.to_i
c = Car.new
c.set_make(make)
c.set_model(model)
c.set_year(year)
array_of_cars << c
end
puts
puts "You have the following cars: "
for car in array_of_cars
print "#{car.get_year} #{car.get_make} #{car.get_model}"
end
end
答案 0 :(得分:0)
好的,所以主要问题是你调用了定义Car.new
类的Car
。你不应该在汽车类中有一系列汽车。您可以尝试创建一个包含汽车数组的Dealership
类,然后您可以执行类似这样的操作
class Dealership
attr_accessor :car_lot
def initialize
@car_lot = []
end
def add_car(car)
@car_lot << car
end
end
crazy_carls = Dealership.new
car1 = Car.new(make, model, year)
crazy_carls.add_car(car1)
crazy_carls.car_lot.each do |car
print "#{car.get_year} #{car.get_make} #{car.get_model}"
end
首先需要对汽车类进行重构,然后研究如何使用initialize方法,attr_accessor和instance variables。