0

I'm preparing tests in Ruby/Cucumber/Calabash. I have a text file full of logs. I need to check if specific line/sentence is present in the logs e.g "Please answer my question". I assume that every word independently is present few times, but in this line only once. I need to return TRUE. So far when I tried with:

def check_file( file, string )
  File.open( file ) do |io|
    io.each {|line| line.chomp! ; return line if line.include? string}
  end

  nil
end

and it's always working even string doesn't exist (I'm not sure why?)

Should I try arrays?

Wes Foster
  • 8,770
  • 5
  • 42
  • 62
Karina
  • 1
  • 2
  • 1
    How could it ever return `true` when the last line is `nil`? You want to use [Enumerable #find](http://ruby-doc.org/core-2.3.1/Enumerable.html#method-i-find),not [IO.each](http://ruby-doc.org/core-2.3.0/IO.html#method-i-each) if you just want to know if the string is present at least once in the file. (`IO` `include`s `Enumerable`.) – Cary Swoveland May 01 '16 at 23:48
  • Can you show how it's being called? – Anthony E May 01 '16 at 23:48

1 Answers1

1

Here is a method that does what you want, quite simply. Like yours, it returns the line when there is a match, and nil when there is none.

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

You can test the method's return value for truthiness to see if anything was found:

if check_file(myfile, mystring)
  # ....
Keith Bennett
  • 4,722
  • 1
  • 25
  • 35