编写 Ruby 类方法并获得意外的令牌 kEND 错误

问题描述

我正在编写一个类 Wrapper,并给它一个类方法 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

诚然,您看到的错误消息令人困惑/误导。

但是,如果您使用具有语言感知语法突出显示功能的 IDE(我强烈建议所有程序员,使用所有语言,将其设置为开发的高优先级),那么这至少应该突出显示导致问题的代码行。

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...