我想在我的一个模型范围内返回自定义集合。 但是当我在lambda范围内使用do end block时,我不知道为什么它显示错误。 我使用rails 4.1.0和ruby 2.1.2 ..
这是我的模型中的范围代码:
scope :date, -> (from_date, to_date) do
buff_matches = where match_start_time: from_date..to_date
matches = {}
buff_matches.each do |match|
buff_date = match.match_start_time.to_date.to_s
matches[buff_date] ||= []
matches[buff_date] << match
end
matches
end
它将在此行显示错误: buff_matches.each do | match | 并显示错误消息:SyntaxError:match.rb:15:语法错误,意外的keyword_do_block,期望keyword_end。
但如果我将我的代码更改为:
scope :date, -> (from_date, to_date) do
buff_matches = where match_start_time: from_date..to_date
matches = {}
buff_matches.each { |match|
buff_date = match.match_start_time.to_date.to_s
matches[buff_date] ||= []
matches[buff_date] << match
}
matches
end
它会正常工作。我想使用do end语法,因为它看起来比使用花括号更清晰。你知道为什么会发生这个错误吗?
答案 0 :(得分:1)
看起来你遇到了一个边缘案例。我无法解释为什么它会失败,但这会修复它并使用do..end blocks
scope :date, lambda do |from_date, to_date|
buff_matches = where match_start_time: from_date..to_date
matches = {}
buff_matches.each do |match|
buff_date = match.match_start_time.to_date.to_s
matches[buff_date] ||= []
matches[buff_date] << match
end
matches
end