【问题标题】:Ruby: How do I stop execution and print a string in a loop?Ruby:如何停止执行并在循环中打印字符串?
【发布时间】:2013-07-23 02:58:10
【问题描述】:

我正在编写一个 rake 任务。问题是我想在if keeper.has_trevance_info? && candidate.has_trevance_info? 为真时停止执行任务。我只想让它在日志中打印Another record already has that info! 并停止任务。我该怎么做?是raise 还是throw

  billing_infos.each do |candidate|
    unless keeper.nil?
      raise "Another record already has that info! Manually compare BillingInfo ##{keeper.id}
             and ##{candidate.id}" if keeper.has_trevance_info? && candidate.has_trevance_info?

    else
      keeper = candidate
    end

  end

【问题讨论】:

    标签: ruby-on-rails ruby rake raise


    【解决方案1】:

    您不想使用异常处理来退出任务。您可以使用“中止”或“退出”。

    所以你的代码会做这样的事情:

    billing_infos.each do |candidate|
      unless keeper.nil?
        if keeper.has_trevance_info? && candidate.has_trevance_info?
          puts "Another record already has that info! Manually compare BillingInfo ##{keeper.id}"
          exit
        end
      else
        keeper = candidate
      end
    end
    

    或者:

    billing_infos.each do |candidate|
      unless keeper.nil?
        abort("Another record already has that info! Manually compare BillingInfo ##{keeper.id}") if keeper.has_trevance_info? && candidate.has_trevance_info?
      else
        keeper = candidate
      end
    end
    

    【讨论】:

    • 谢谢!退出/中止是我正在寻找的方法!两者有区别吗?
    • @Edmund abort 允许您指定消息。除此之外,我认为它们具有相同的影响。这里有一个很好的讨论:stackoverflow.com/questions/2316475/…
    猜你喜欢
    • 2022-12-05
    • 2021-03-09
    • 2012-07-07
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多