我要求用户输入,并将其作为哈希存储在数组中。我需要从这些哈希中提取共享相同键的值。我想打印属于同一群组的学生的姓名,如下所示:
"May cohort students are: Brian, Penelope"
"June cohort students are: Fred, Pedro"
我怎么能这样做?我需要这个方法的帮助:
def print(students)
#go through all hashes in 'students' and group them by cohort
#print each cohort separately
end
所以我可以使用map
和select
:
def input_students
puts "Please enter the names of the students"
puts "To finish, just hit return twice"
students = []
name = gets.chomp
puts "In which cohort is this student?"
cohort = gets.chomp
while !name.empty? do
students << {cohort.to_sym => name}
name = gets.chomp
cohort = gets.chomp
end
students
end
students = input_students
print(students)
但我得到:
"no implicit conversion of Symbol to Integer"
首先,我建议更改input_students
,因为输入名称和同类群组的提议只显示一次。并且用户无法理解输入的内容。
另外我建议更改此方法的返回值。
def input_students
puts "Leave field empty to finish"
puts
students = []
loop do
puts "Please enter the name of the student"
name = gets.chomp
break if name.empty?
puts "In which cohort is this student?"
cohort = gets.chomp
break if cohort.empty?
students << { cohort: cohort, name: name }
end
students
end
def print(students)
students.
map { |s| s[:cohort] }.
uniq.
each { |c| puts "#{c} cohort students are #{students.
find_all { |s| s[:cohort] == c }.
map { |s| s[:name] }.
join(', ')}" }
end
students = input_students
print(students)
# First we get an array of cohorts of all students.
# The number of elements in the array is equal to the number of students
students.map { |s| s[:cohort] }
# But many students are in the same cohort.
# To avoid this duplication, get rid of duplicates.
students.map { |s| s[:cohort] }.uniq
# Well done. Now we have an array of unique cohorts.
# We can use this to print information about each cohort.
students.map { |s| s[:cohort] }.uniq.each { |c| puts "Cohort information" }
# How to print information? For each cohort certain actions are carried out.
# First, find all the students in this cohort.
students.find_all { |s| s[:cohort] == c }
# We only need the names of these students.
students.find_all { |s| s[:cohort] == c }.map { |s| s[:name] }
# But this is an array of names. Convert it to a string, separated by commas.
students.find_all { |s| s[:cohort] == c }.map { |s| s[:name] }.join(', ')