如果我可以得到一些关于打印出用户输入的数据的分配问题的帮助,我将非常感激(在这个具体的例子中,年,模型和使汽车的):需要一些帮助定义一些方法
# DEFINE YOUR CAR CLASS HERE
# create empty array
array_of_cars = Array.new
# prompt for and get number of cars
print "How many cars do you want to create? "
num_cars = gets.to_i
# create that many cars
for i in 1..num_cars
# get the make, model, and year
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
# create a new Car object
c = Car.new
# set the make, model, and year
# that we just read in
c.set_make(make)
c.set_model(model)
c.set_year(year)
# add the Car object to the array
array_of_cars << c
end
# print out the information for
# the Car objects in the array
puts
puts "You have the following cars: "
for car in array_of_cars
puts "#{car.get_year} #{car.get_make} #{car.get_model}"
end
我已经有程序的某些部分,但它的主要部分挣扎,因为我那种知道该怎么做,但不是如何实现它。
因此,对于这部分:#定义你的车类HERE
我得到这个:
class Car
def assign(m,n,y)
#instance variables
@make = m
@model = n
@year = y
end
#instance methods
def set_make
end
def set_model
end
def set_year
end
def get_make
end
def get_model
end
def get_year
end
首先,我才这样做的权利与实例变量?
然后,“设置”的目的是将值保存到数组中吗?然后“get”让我稍后提取它们。我想我会理解这个概念,如果有人能告诉我如何定义其中的一个。
我知道这看起来有点含糊,所以我会尽力澄清是否有问题发生。也很抱歉的文字墙,谢谢你!
你好,首先非常感谢你对你的反应,但是,让我们说,我不希望使用attr_accessor。在课堂上单独定义的一个吸气和吸气器,更复杂的方法会如何?如果你不介意的话,如果你能演示一个例子,我将不胜感激。例如,如果我有:c.set_make(make),它将如何在类中定义? –
用手动声明的getter和setter更新了答案。 – mudasobwa
谢谢!先生,祝你有美好的一天 –