【发布时间】:2016-10-27 18:57:55
【问题描述】:
在这个方法的最后,我创建了我已经尝试过 sort_by 的群组。但是,当我这样做时,它会返回一条错误消息:
directory.rb:75: syntax error, unexpected ']'
bycohort = students.sort_by { |v| v[cohort:] }
我已经尝试了很多方法,包括:
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[:cohort]而不是v[cohort:]。
标签: arrays ruby sorting hash enumeration