Jack Kelly Jack Kelly - 1 month ago 8
Ruby Question

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

At the end of this method, I have created I have tried to sort_by cohorts. However when I do this it throws back an error saying:

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


I have tried this sort_by method a number of ways including:

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


Please, could someone tell me how this method works and why. I'm confused.

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

Answer

not

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

but

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

This is the right syntax. { key: value } is the literal syntax to create an hash with a symbol key but this is not the case.

Comments