2

I am trying to make sense of why Ruby reported the syntax error that it did , and why it could not be more clear. The following code snippet is giving me a "syntax error, unexpected end"

# @param {NestedInteger[]} nested_list
# @return {Integer}
def depth_sum(nested_list)
  queue = Queue.new

  nested_list.each { |element| queue.enq element }

  result = 0
  level  = 1
  until queue.empty?
    size = queue.size
    size.times do
      element = queue.pop
      if element.is_integer
        result += level * element.get_Integer
      else
        element.each { |elem| queue.enq(elem) }
      end
    end
    level++
  end
end

I then figured out that Ruby does not have the ++ operator , so i replaced level++ with level+=1 and the code worked. But why was Ruby's syntax error message so cryptic about an unexpected end when in fact my error was not due to the "end" but because I was using a ++ operator which is not used in Ruby.

zulu-700
  • 47
  • 5

1 Answers1

2

In Ruby, it is allowed to have whitespace between an operator and its operand(s). This includes newlines, and it includes unary prefix operators. So, the following is perfectly valid Ruby:

+
foo

It is the same as

+ foo

which is the same as

+foo

which is the same as

foo.+@()

The following is also perfectly valid Ruby:

foo++
bar

It is the same as

foo ++ bar

which is the same as

foo + + bar

which is the same as

foo + +bar

which is the same as

foo.+(bar.+@())

So, as you can see, the line

level++

on its own is not syntactically invalid. It is the end on the next line that makes this invalid. Which is exactly what the error message says: you are using the unary prefix + operator, so Ruby is expecting the operand, but instead finds an end it was not expecting.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653