如何从哈希中提取键中的所有值

时间:2019-03-26 20:36:03

标签: arrays ruby hash

我要求用户输入,并将其存储为散列在数组中。我需要从那些散列中提取共享相同密钥的值。我想像这样打印属于同一群组的学生的姓名:

"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

以便我可以使用mapselect

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"

1 个答案:

答案 0 :(得分:0)

首先,我建议更改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(', ')