【问题标题】:syntax error, unexpected keyword_rescue, expecting keyword_end语法错误,意外的keyword_rescue,期待keyword_end
【发布时间】:2018-08-07 11:55:03
【问题描述】:

我有以下红宝石代码:

  EmailTemplate.for(mailer).each do |template|
    begin
      print '.'
      template.upload(publish)
    rescue Mandrill::UnknownTemplateError
      failed.push(mailer)
    end
  end

Rubocop 将我的代码更正为:

EmailTemplate.for(mailer).each do |template|
    print '.'
    template.upload(publish)
  rescue Mandrill::UnknownTemplateError
    failed.push(mailer)
  end

现在它返回以下错误:

syntax error, unexpected keyword_rescue, expecting keyword_end

我该如何解决这个问题?

Rubocop 警告是:

C: Style/RedundantBegin: Redundant begin block detected.

【问题讨论】:

  • 你的 Ruby 版本是什么?
  • 第一个版本我觉得不错。
  • 我的 Ruby 版本是 2.4.1。

标签: ruby rubocop


【解决方案1】:

Ruby 2.5.0 添加了feature

rescue/else/ensure 现在可以直接与 do/end 块一起使用。 [功能 #12906]

但在那之前,这是不允许的。所以会有语法错误。

让我们对 sample.rb 中的代码进行语法测试:

[].each do |a|
  # ops
  rescue Exception => ex
  puts ex.inspect
end

从终端:

Ruby$ ruby -c sample.rb
sample.rb:3: syntax error, unexpected keyword_rescue
  rescue Exception => ex
        ^
sample.rb:5: syntax error, unexpected keyword_end, expecting end-of-input
Ruby$ rvm use 2.5.1
Using /Users/aruprakshit/.rvm/gems/ruby-2.5.1
Ruby$ ruby -c sample.rb
Syntax OK

请参阅News。所以在2.5.0之前,需要这样写:

[].each do |a|
  begin
    # ops
  rescue => Exception
    puts ex.inspect
  end
end

您可以通过关注Setting the target Ruby version 来配置 Rubocop 以选择您想要的 Ruby 版本。

某些检查取决于 Ruby 解释器的版本 检查的代码必须继续运行。例如,使用 Ruby 2.3+ 执行 安全导航运算符而不是尝试可以帮助您编写代码 更短更一致...除非它必须在 Ruby 2.2 上运行。

如果 .ruby-version 存在于调用 RuboCop 的目录中, RuboCop 将使用它指定的版本。否则,用户可能会让 RuboCop 知道您的项目支持的最旧版本的 Ruby 与:

AllCops:
  TargetRubyVersion: 2.4

【讨论】:

    【解决方案2】:

    出于某种原因,Rubocop 认为您运行的是 Ruby 2.5,而不是 Ruby 2.4.1。

    您可以通过以下两种方式之一解决此问题:

    1) 创建一个文件.ruby-version,内容为2.4.1。 Rubocop 应该从此文件中获取您的 Ruby 版本。
    2)将以下内容添加到您的.rubocop.yml

    AllCops:
      TargetRubyVersion: 2.4
    

    【讨论】:

      猜你喜欢
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多