【问题标题】: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 方法时收到错误消息。我该如何解决这个问题?
【发布时间】: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


【解决方案1】:

不是

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

但是

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

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

【讨论】:

  • @JackKelly 如果它能让事情变得不那么混乱,你也可以像这样在哈希中分配东西:a = {:key =&gt; value}
  • 谢谢 Eli,为了简单起见,我可能会开始这样做。
  • @JackKelly:散列文字的一般语法是{ key =&gt; value }(但如果散列文字是方法调用的最后一个参数,您可以去掉大括号)。如果key 是一个符号,那么您可以说{ key: value },但这仅适用于键是符号文字并且您正在编写散列文字的情况。符号文字在其他任何地方都有一个前导冒号。这是与 Ruby 混淆的一个非常常见的原因。
猜你喜欢
  • 2023-01-07
  • 1970-01-01
  • 1970-01-01
  • 2018-04-27
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
相关资源
最近更新 更多