ruby - 语法错误,意外的 keyword_rescue,期待 keyword_end

标签 ruby rubocop

我有以下 ruby 代码:

  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 2.5.0 添加了一个 feature :

rescue/else/ensure are now allowed to be used directly with do/end blocks. [Feature #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 版本.

Some checks are dependent on the version of the Ruby interpreter which the inspected code must run on. For example, enforcing using Ruby 2.3+ safe navigation operator rather than try can help make your code shorter and more consistent... unless it must run on Ruby 2.2.

If .ruby-version exists in the directory RuboCop is invoked in, RuboCop will use the version specified by it. Otherwise, users may let RuboCop know the oldest version of Ruby which your project supports with:

AllCops:
  TargetRubyVersion: 2.4

关于ruby - 语法错误,意外的 keyword_rescue,期待 keyword_end,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51726190/

相关文章:

ruby-on-rails - Rails 应用程序无法连接到 postgresql,但 rake、rails c 和 rails db 可以

ruby - 如何在不构建的情况下安装 gem

ruby - 如何在Ruby中正确编写代码?这样它就会产生正确的输出?

ruby-on-rails - Rubocop/Hound 建议卡住字符串文字类名

ruby - 为什么行数太多的方法是一件坏事?

ruby-on-rails - 如何在 Capybara 中获取父节点?

ruby - Twilio:Ruby:并行运行的调用的回调状态 URL:哪个调用已完成?

ruby - 如何将 Rubocop 与 Rake 集成?

ruby - 如何在每次保存时使用 Rubocop 使 RubyMine 自动更正

ruby-on-rails - rails : rubocop disable Class has too many lines error