В конце этого метода, который я создал, я попытался сортировать когорты. Однако, когда я делаю это он откидывает ошибку говоря:Я получаю сообщение об ошибке, когда пытаюсь использовать метод 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
Ваш вопрос не использует метод неправильно, но неверно использует индекс. Индексирование хэшей похоже на это 'v [: когорт]' not 'v [когорт:]'. –