编写 Ruby class 方法并出现意外令牌 kEND 错误

Writing a Ruby class method and getting unexpected token kEND error

我正在写一个 class、Wrapper,并给它一个 class 方法 self.wrap。我收到 unexpected end-of-input 错误。我一直盯着代码看,看不出错误在哪里。我想我的 end 都准备好了。我错过了什么?

require 'pry'
class Wrapper
    def self.wrap(input_string, column_number)
        position = 0
        num_inserted = 0
        while (position + column_number < line.length) do
            last_space_index = input_string.rindex(" ", position + column_number)
            if last_space_index > position - 1
                input_string[num_inserted + last_space_index] = "\n"
            else
                input_string.insert(num_inserted + position + column_number, "\n")
                position += column_number
                num_inserted ++
            end
        end
    end
end

There is no ++ operator in Ruby.

相反,您可以这样写:

num_inserted = num_inserted + 1

或简称:

num_inserted += 1

您看到的错误消息确实相当 confusing/misleading。

但是,如果你使用带有语言感知语法高亮的IDE(我强烈推荐所有程序员,在所有语言中,设置为高开发优先级)那么这至少应该突出显示导致问题的代码行。

例如,在我的本地设置中输入您的代码会显示错误:

`+' after local variable or literal is interpreted as binary operator
even though it seems like unary operator