简体   繁体   中英

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 &. 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.

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.

To get this working just remove the for keyword as anyways you can get this accomplished using each as well.

 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

all_items.each_with_index do |key, value|

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM