我是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)