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.

3
  • There's no such ++ operator in Ruby. Try with level += 1. Commented Mar 19, 2020 at 11:18
  • See related. Commented Mar 19, 2020 at 11:19
  • 1
    It's probably because 1 ++ 1 is parsed as 1 + ( +1), so it needs the second operand but the Ruby met end at its place in your example, hence the error. But it's only my supposition. Commented Mar 19, 2020 at 11:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.