当我尝试在我的哈希数组上使用 sort_by 方法时收到错误消息。我该如何解决这个问题?

I am recieving an error when I try to use the sort_by method on my array of hashes. How do i solve this?

在这个方法的最后,我创建了我尝试过的 sort_by 队列。但是,当我这样做时,它会返回一条错误消息:

directory.rb:75: syntax error, unexpected ']'
bycohort = students.sort_by { |v| v[cohort:] }

我已经尝试过这个 sort_by 方法,包括:

 bycohort = students.sort_by { |k,v| v[cohort:] }

拜托,谁能告诉我这个方法是如何工作的以及为什么。我很困惑。

def input_students
  puts "Please enter the names and then the cohort of the students"
  puts "To finish, just hit return twice"
  #created an empty array
  students = []
  #getting the first name
  name = gets.chomp
  cohort = gets.chomp.to_sym
     if cohort.empty?
         cohort = :november
     end

     if cohort !~ /january|february|march|april|may|june|july|august|september|october|november|december/
puts "Please enter a valid month"
puts "Warning months are case sensitive. Please enter in lowercase characters."
 cohort = gets.chomp.to_sym
end

while !name.empty? do
# add the student hash to the array called students
students << {name: name, cohort: cohort}
puts "Now we have #{students.count} students"
#getting another name from the user
name = gets.chomp
cohort = gets.chomp.to_sym

if cohort.empty?
  cohort = :november
end

if cohort !~ /january|february|march|april|may|june|july|august|september|october|november|december/
  puts "Please enter a valid month"
  puts "Warning months are case sensitive. Please enter in lowercase characters."
   cohort = gets.chomp.to_sym
end

end
  bycohort = students.sort_by { |v| v[cohort:] }
  bycohort
end

没有

bycohort = students.sort_by { |v| v[cohort:] }

但是

bycohort = students.sort_by { |v| v[:cohort] }

这是正确的语法。 { key: value } 是用符号键创建哈希的文字语法,但事实并非如此。