如何从内部块停止外部块

How to stop outer block from inner block

我尝试实现查找特定 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 之外,它会起作用,但这不是我想要的。

我该如何处理?

提前致谢。

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

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