如何从内部块阻止外部块

时间:2015-05-01 08:05:34

标签: ruby command-line

我尝试实现查找特定keyword的匹配项的搜索功能,但如果提供了--max个选项,则只打印一些特定数量的行。

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

我尝试使用break语句,但当它在if ... end块内时,我无法从外部each_with_index块中突破。

如果我将break移到if ... end之外就行了,但这不是我想要的。

我该如何处理?

提前致谢。

1 个答案:

答案 0 :(得分:1)

我不确定如何在你的代码中实现它,因为我还在学习Ruby,但你可以尝试catch并抛出来解决这个问题。

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

这样的事情已经存在here