代码之家  ›  专栏  ›  技术社区  ›  Mateusz Urbański

语法错误,意外的关键字营救,应为关键字结束

  •  2
  • Mateusz Urbański  · 技术社区  · 8 年前

    我有以下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.
    
    2 回复  |  直到 8 年前
        1
  •  5
  •   Nils Landt    8 年前

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

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

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

    AllCops:
      TargetRubyVersion: 2.4
    
        2
  •  6
  •   Arup Rakshit    8 年前

    Ruby 2.5.0增加了 feature :

    rescue/else/ensure现在允许直接与do/end blocks一起使用。[特征#12906]

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

    让我们对中的代码进行语法测试 示例.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
    

    您可以配置Rubocop来选择您想要的Ruby版本,方法如下 Setting the target Ruby version .

    有些检查依赖于Ruby解释器的版本 检查的代码必须在上运行。例如,使用Ruby 2.3实现+ 安全的导航操作员而不是尝试可以帮助您的代码 更短更一致。。。除非它必须在Ruby 2.2上运行。

    如果Ruby版本存在于目录中,则调用RuboCop, RuboCop将使用它指定的版本。否则,用户可以 RuboCop知道您的项目支持的最老版本的Ruby 使用:

    AllCops:
      TargetRubyVersion: 2.4
    
    推荐文章