2017-08-01 143 views
1

我正在写一个简短的程序,要求用户输入汽车模型,制造商和年份输入,并通过算法传递该输入。我的问题是,是否有方法在通过公式将多个打印输出标记为每个输出的编号后标注多个打印输出?我需要为每个循环使用一个吗?我只是想了解我将如何完成这一任务。例如Ruby标签打印输出

例如打印输出看起来像这样。

class Car 
    attr_reader :make, :model, :year 
    def initialize 
    end 

    def set_make(make) 
     @make = make 
    end 

    def set_model(model) 
     @model = model 
    end 

    def set_year(year) 
     @year = year 
    end 

    def get_make 
     @make 
    end 

    def get_year 
     @year 
    end 

    def get_model 
     @model 
    end 
end 


array_of_cars = Array.new 

print "How many cars do you want to create? " 
    num_cars = gets.to_i 

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: " 
puts 
for car in array_of_cars 
    puts "#{car.get_year} #{car.get_make} #{car.get_model}" 
end 
puts 
  1. 2014福特Expedition
  2. 2017年丰田86
  3. 2017年阿斯顿·马丁DB11

是有办法的号码添加到输出?

回答

2

而不是使用for循环中,您可以尝试使用each_with_index,这将使你得到array_of_cars也是每个元素的索引中的每一个元素,在这种情况下,加1到当前索引会给你从开始值1:

array_of_cars.each_with_index do |car, index| 
    puts "#{index + 1}. #{car.get_year} #{car.get_make} #{car.get_model}" 
end 

或者你可以使用eachwith_index传递的第一要素,在这种情况下,1作为参数:

array_of_cars.each.with_index(1) do |car, index| 
    puts "#{index}. #{car.get_year} #{car.get_make} #{car.get_model}" 
end 
+0

谢谢你向我展示如何得到它! –

+0

不用客气,也可以参考1..num_cars部分的''我也可以看看[Ruby#Enumerator](https://ruby-doc.org/core-2.2.0/ Enumerator.html)。 –

0

你不”需要这么多方法。使用attr_accessor来设置获取者和设置者,并更好地利用initialize。然后使用tadman的这个answer的基本思想,我们可以将新创建​​的对象收集到类中的一个数组中。总之,我们可以压缩你的类:

class Car 
    attr_accessor :make, :model, :year 

    def self.all 
    @all ||= [] 
    end 

    def initialize(make, model, year) 
    @make = make 
    @model = model 
    @year = year 
    Car.all << self 
    end 

end 

我们可以使用times运行一段代码n倍。

puts "How many cars do you want to create? " 
n = gets.to_i 

n.times.with_index(1) { |_,i| 
    puts "Enter make for car #{i}" 
    make = gets.chomp 

    puts "Enter model for car #{i}: " 
    model = gets.chomp 

    puts "Enter year of car #{i}: " 
    year = gets.to_i 
    puts 
    Car.new(make, model, year) 
} 

然后塞巴斯蒂安帕尔马已经提出,用each.with_index(1)打印您的汽车。使用for循环用Ruby 2.使用putsprint 1.忌:1。

Car.all.each.with_index(1) { |c, i| puts "#{i}. #{c.year} #{c.make} #{c.make}" } 

图片的标题说明偏移指数的参数。