[英]Ruby on Rails syntax error, unexpected '\n', expecting &. or :: or '[' or '.'
I have a module with this error: 我有一个出现此错误的模块:
... /gather_descendants.rb:39: syntax error, unexpected '\\n', expecting &.
... /gather_descendants.rb:39:语法错误,意外的“ \\ n”,期望&。 or :: or '[' or '.'
或::或'['或'。
If I comment out the whole for loop from lines 34 - 39, the error disappears, but if I comment out the unless block inside of it from line 36-38, it remains. 如果我从第34-39行注释掉整个for循环,错误消失了,但是如果我从第36-38行注释掉了它内部的“除非”块,它仍然存在。
module GatherDescendants
def gather_descendants_for(id)
@descendants = Comment.select{ |item| item[:parent_id] == id }
end
def make_hash_tree_for(arr)
has_parent = Set.new
all_items = {}
arr.each do |comm|
parent = arr.find { |c| c.id ==comm.parent_id }
# if parent not in all_items
if all_items.select { |c| c.id == comm.parent_id }.size == 0
# all_items[parent] = {}
all_items[parent] = {}
end
# if child not in all_items
if all_items.select { |c| c.id == comm.parent_id }.size == 0
# all_items[child] = {}
all_items[comm] = {}
end
# all_items[parent][child] = all_items[child]
all_items[parent][comm] = all_items[comm]
# has_parent.add(child)
has_parent.add(comm)
result = {}
# for key, value in all_items
for all_items.each do |key, value| # <-- line 32
# if key not in has_parent
unless has_parent.key?(key) # <-- line 36
result[key] = value
end # <-- line 38
end # <-- line 39
end
@tree = result
end
end
Any idea what could be causing this? 知道是什么原因造成的吗?
As per the description and code snippet shared , it shows that you are using two different indenpendent ways combined on single array to iterate over it. 根据共享的描述和代码片段,它表明您在单个数组上使用两种不同的独立方式进行迭代。
for all_items.each do |key, value| # <-- line 32
Above line shows that first you are using for and then you have also specified each on the all_items array. 上面的行显示,首先要使用for,然后再在all_items数组上指定它们。
To get this working just remove the for keyword as anyways you can get this accomplished using each as well. 要使此工作正常进行,只需删除for关键字即可,无论如何,您也可以使用每个关键字来完成此工作。
all_items.each do |key, value| # <-- line 32
With the above modified line the syntax error would not appear. 通过上面的修改行,不会出现语法错误。
if you use it as an index and value. 如果将其用作索引和值。 You must use each_with_index
您必须使用each_with_index
all_items.each_with_index do |key, value|
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.