使用 Ruby gets.chomp 方法向用户询问多个问题



我对Ruby很陌生,并且使用用户输入进行练习。我已经编写了以下内容,允许用户连续输入学生的姓名,直到他们点击两次回车。每次输入后,程序都会返回学校中有多少学生,当他们完成输入后,它会打印出学生和他们所在的队列的列表。

目前,队列

是硬编码的,我想修改它,以便我可以同时询问名称和队列,程序继续询问此信息,直到用户点击返回两次。任何帮助将不胜感激 - 谢谢:)

  puts "Please enter the names of the students"
  puts "To finish, just hit return twice"
  students = []
  name = gets.chomp
  while !name.empty? do 
    students << {name: name, cohort: cohort} 
    puts "Now we have #{students.count} students" 
    name = gets.chomp
  end
  students
end
def print_header
  puts "The students of this Academy".center(50)
  puts "-----------".center(50)
end
def print(students)
 students.each do |student, index|
   puts "#{student[:name]} #{student[:cohort]} cohort"
    end
 end
end
def print_footer(names)
  puts "Overall, we have #{names.count} great students".center(50)
end
students = input_students
print_header
print(students)
print_footer(students)

我建议使用循环 do 并在name为空(或也cohort(的情况下使用 loop do 和中断,而不是 while 循环:

loop do 
  puts "Please enter the names of the students"
  name = gets.chomp
  break if name.empty?
  puts "Please enter the cohort"
  cohort = gets.chomp
  # break if cohort.empty?
  students << {name: name, cohort: cohort} 
end

最新更新