1

I try to implement search function which looks for occurrence for particular keyword, but if --max options is provided it will print only some particular number of lines.

def search_in_file(path_to_file, keyword)
  seen = false
  File::open(path_to_file) do |f|
    f.each_with_index do |line, i|
      if line.include? keyword

        # print path to file before only if there occurence of keyword in a file
        unless  seen
          puts path_to_file.to_s.blue
          seen = true
        end

        # print colored line
        puts "#{i+1}:".bold.gray + "#{line}".sub(keyword, keyword.bg_red)


        break if i == @opt[:max]  # PROBLEM WITH THIS!!! 

      end



    end
  end
  puts "" if seen
end

I try to use break statement, but when it's within if ... end block I can't break out from outer each_with_index block.

If I move break outside if ... end it works, but it's not what I want.

How I can deal with this?

Thanks in advance.

SuperManEver
  • 2,263
  • 6
  • 28
  • 36
  • 1
    Why don't you want to move that `break if i == @opt[:max]` line out if the `if` block? Btw your current implementation has the problem that it does not stop if the line with `@opt[:max]` number doesn't include the keyword. You have to change that anyway. – spickermann May 01 '15 at 08:22
  • The point is, to check only lines where occurrence was found and stop when maximum reached. If I will do it in your way it will count all line, 10 for example, and stops. What I want is to count lines only with occurrence. – SuperManEver May 01 '15 at 08:37
  • @spickermann your comment indirectly pointed me to where real problem is. Actually I do comparison on the wrong variable – SuperManEver May 01 '15 at 08:43

1 Answers1

1

I'm not sure how to implement it in your code as I'm still learning Ruby, but you can try catch and throw to solve this.

def search_in_file(path_to_file, keyword)
  seen = false
  catch :limit_reached do
  #put your code to look in file here...
  throw :limit_reached if i == @opt[:max] #this will break and take you to the end of catch block

Something like this already exist here

Community
  • 1
  • 1
T.Aoukar
  • 653
  • 5
  • 19
  • Actually, the problem was not with how I break out of block, but with how I count lines and check condition to break. – SuperManEver May 01 '15 at 08:41