我已经尝试过:
elsif file.grep(/Mode: 1/)
puts "test"
else
puts "test but else"
Codacy 表示这是错误的。有没有办法改善这一点?根据 Codacy:
unexpected token kELSIF (Using Ruby 2.2 parser; configure using `TargetRubyVersion` parameter, under `AllCops`)
unexpected token kELSE (Using Ruby 2.2 parser; configure using `TargetRubyVersion` parameter, under `AllCops`)
最佳答案
您可以使用IO::read
分配文本文件内容,然后 String#include?
用于检查。
file_string = File.read('path/to/file')
if file_string.include?('substring')
puts 'Yes'
else
puts 'No'
end
您也可以将其替换为 String#match?
(更快)。
file_string.match?(/pattern/)
将返回 true
或 false
。
关于ruby - 如何扫描文本文件中的字符串,并在字符串不存在时运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55363487/