簡體   English   中英

使用 Ruby gets.chomp 方法向用戶詢問多個問題

[英]Asking a user multiple questions using Ruby gets.chomp method

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

我建議使用循環 dobreak代替while循環,以防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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM