gpt4 book ai didi

ruby - Rubocop 是 "ruby -c"语法检查的超集吗?

转载 作者:数据小太阳 更新时间:2023-10-29 07:51:47 25 4
gpt4 key购买 nike

我们进行了一项测试,找到应用程序中的每个 Ruby 文件并对其运行 ruby -c。我们介绍了Rubocop并让它检查相同的文件列表。

运行 ruby -c 的测试现在实际上是无用的,还是有一个失败模式的例子可以被 ruby -c 而不是 Rubocop 捕获?

ruby -c 的文档说:

Causes Ruby to check the syntax of the script and exit without executing. If there are no syntax errors, Ruby will print "Syntax OK" to the standard output.

这是一个语法问题的例子:

% echo "puts 'hello world" > hot_script.rb
% ruby -c hot_script.rb
hot_script.rb:1: unterminated string meets end of file

% rubocop hot_script.rb
Inspecting 1 file
F

Offenses:

hot_script.rb:1:6: F: unterminated string meets end of file
(Using Ruby 1.9 parser; configure using TargetRubyVersion parameter, under AllCops)
puts 'hello world
^

1 file inspected, 1 offense detected

Rubocop 甚至捕获了一些相同的警告,尽管我之前没有配置 ruby -c 来捕获这些警告,因此我对错误更感兴趣。以下是处理警告的相对平等的示例:

% cat unused_var.rb
def hot_method
a = 1
b = 2
puts b
end

% ruby -cwW2 unused_var.rb
unused_var.rb:2: warning: assigned but unused variable - a
Syntax OK

% rubocop unused_var.rb
Inspecting 1 file
W

Offenses:

unused_var.rb:2:3: W: Lint/UselessAssignment: Useless assignment to variable - a.
a = 1
^

1 file inspected, 1 offense detected

我搜索使用

但我可能做错了。测试在 Ruby 1.9 中比在 Ruby 1.8 中慢得多,所以这个问题的答案对我来说实际上很有值(value)。而且您必须承认,您很好奇,对吧?

最佳答案

答案是“大部分时间”。 RuboCop 建立在解析器 gem 之上,它是一个独立的 Ruby 解析器,或多或少地模仿了 MRI 解析器。 RuboCop 包装了解析器的语法检查,并将正确报告问题。但是,正如解析器的 GitHub 上所述:

Unfortunately MRI often changes syntax in patch level versions [...] there is no simple way to track these changes.

This policy makes it all but impossible to make Parser precisely compatible with the Ruby MRI parser.

此外,解析器支持您使用的任何版本的最新次要版本,并且不向后移植次要版本。因此,如果您使用 Ruby 2.4.0,RuboCop 将使用支持 2.4.1 语法的解析器版本。

就所有意图和目的而言,解析器等同于官方 MRI 解析器,除非您有特定的理由同时使用两者,否则单独使用 RuboCop 就足够了。

关于ruby - Rubocop 是 "ruby -c"语法检查的超集吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44189752/

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