我在Ruby / Cucumber / Calabash准备测试。我有一个充满日志的文本文件。我需要检查日志中是否存在特定的行/句子,例如"请回答我的问题"。我假设每个单词独立出现几次,但在这一行只有一次。我需要返回TRUE。到目前为止,当我尝试:
def check_file( file, string )
File.open( file ) do |io|
io.each {|line| line.chomp! ; return line if line.include? string}
end
nil
end
并且它总是在工作,即使字符串也不存在(我不确定为什么?)
我应该尝试数组吗?
答案 0 :(得分:1)
这是一种方法,可以很简单地完成您想要的操作。和你的一样,它在匹配时返回行,如果没有,则返回nil。
def check_file(file, string)
File.foreach(file).detect { |line| line.include?(string) }
end
1.9.3-p551 :007 > check_file 'Gemfile', 'gem'
=> "source 'https://rubygems.org'\n"
1.9.3-p551 :008 > check_file 'Gemfile', 'gemxx'
=> nil
您可以测试方法的真值返回值,看看是否找到了任何内容:
if check_file(myfile, mystring)
# ....