gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:30 26 4
gpt4 key购买 nike

我有以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com