我试图仅打印给定的值,但不输入输入。 如果我打印11月的内容,则只打印学生所在的队列。
我尝试了student.fetch(cohort_input).include?(月) 但不起作用。 有人告诉我我需要创建要检查的月份列表
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
def input_students
puts "Please enter the names of the students"
puts "To finish, just hit return twice"
students = []
while name = gets.chomp do
break if name.empty?
puts "What is your student cohort"
cohort = gets.chomp
puts "Where is your student from"
country_of_birth = gets.chomp
if cohort.empty? || country_of_birth.empty?
cohort = "Not given"
country_of_birth = "(Not given)"
end
students << {name: name, cohort: cohort, country_of_birth: country_of_birth}
if students.count > 1
puts "Now we have #{students.count} students"
else
puts "Now we have #{students.count} student"
end
puts "Enter another name"
end
students
end
def print_header
puts "The students of Villains Academy"
puts "-------------"
end
def print(students)
puts "What cohort would you like to print"
cohort_input = gets.chomp#.capitalize
students.map do |student|
student.map {|k,v| [k, v.to_sym]
}
#puts " #{student[:name]} (#{student[:cohort]} cohort), #{student[:country_of_birth]}"
end
students.each do |student|
if cohort_input == months[]
puts student[:name]
end
end
end
def print_footer(students)
if students.count > 1
puts "Overall, we have #{students.count} great students"
else
puts "Overall, we have #{students.count} great student"
end
end
students = input_students
print_header
print(students)
print_footer(students)```
All kind of errors
答案 0 :(得分:0)
print
方法有点混乱,它正在调用months
变量,该变量不存在。
测试数据集,以防万一有人发现它有用:
students = [{:name=>"Peter", :cohort=>"A", :country_of_birth=>"Here"}, {:name=>"Popeye", :cohort=>"A", :country_of_birth=>"There"}, {:name=>"Tom", :cohort=>"A", :country_of_birth=>"Where"}, {:name=>"Jack", :cohort=>"J", :country_of_birth=>"Here"}, {:name=>"Ron", :cohort=>"J", :country_of_birth=>"There"}, {:name=>"Ross", :cohort=>"R", :country_of_birth=>"Anywhere"}]
使用Array#select尝试类似的操作:
def my_print(students)
puts "What cohort would you like to print"
cohort_input = gets.chomp#.capitalize
students.select{ |s| s[:cohort] == cohort_input }.each {|student| p student }
end
旁注,请勿使用print
作为方法名称。