ruby 如何从散列中的键中提取所有值[关闭]

esbemjvw  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(126)

已关闭,此问题需要details or clarity。它目前不接受回答。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

4年前关闭。
Improve this question
我要求用户输入,并将其存储为数组中的散列。我需要从这些散列中提取共享相同键的值。我想打印属于同一队列的学生的姓名,如下所示:

"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"
bkkx9g8r

bkkx9g8r1#

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

相关问题