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

问题描述 投票:-1回答:1

我是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)
ruby
1个回答
0
投票

而不是while循环,我建议使用loop dobreak以防name为空(或cohort):

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
© www.soinside.com 2019 - 2024. All rights reserved.