【问题标题】:Writing a Ruby class method and getting unexpected token kEND error编写 Ruby 类方法并得到意外的令牌 kEND 错误
【发布时间】:2021-01-13 07:58:48
【问题描述】:

我正在写一个类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

【问题讨论】:

  • (字面)错误信息是否“unexpected token kEND error”

标签: ruby syntax-error unexpected-token


【解决方案1】:

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

【讨论】:

  • 你能推荐一个IDE吗?
  • 有很多文章深入讨论了您的选择,例如this。我个人喜欢Vim 的速度和跨设备可靠性,或者VSCode 更增强的GUI。归根结底,使用什么并不重要,但是如果您的编辑器没有自动为您标记上述语法错误,那么您就是在手铐上进行开发。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-11
  • 2011-07-05
  • 1970-01-01
  • 2015-11-27
  • 2016-10-31
  • 1970-01-01
相关资源
最近更新 更多