代码之家  ›  专栏  ›  技术社区  ›  Adam Taylor

为什么我不能“打破”这个红宝石块?

  •  0
  • Adam Taylor  · 技术社区  · 14 年前

    我有一块红宝石:

        status = ''
        build.parse do |entry|
            puts "parsing an item"
            puts entry.title
    
            if entry.title =~ /FAILURE/ then
                puts "failure"
                status = "FAILURE"
            else 
                status = "SUCCESS"
            end
            puts status
            break entry if status == "FAILURE"
        end
    

    http://macruby.labs.oreilly.com/ch03.html#_xml_parsing

    老实说,我的Ruby很差,但我正在尝试编写一个涉及RSS解析的mac应用程序。

    干杯,

    亚当

    2 回复  |  直到 14 年前
        1
  •  4
  •   Jed Schneider    14 年前

    你不需要在if块中使用“then”

    @entries = ["this is a FAILURE", "this is a success"]
    status = ''
    @entries.each do |entry|
      if entry =~ /FAILURE/
        puts "failure"
        status = "failure"
      else
        status = "success"
      end
      puts "status == #{status}"
      break if status == "failure"
    end
    

    作为旁注,将其写为:

    status = @entries.any?{|e| e =~ /FAILURE/} ? 'failure' : 'succes'
    

    在处理可枚举对象(如数组)时,最好使用Ruby内置的工具。

    http://apidock.com/ruby/Enumerable/any%3F

        2
  •  1
  •   JRL    14 年前

    break if status == "FAILURE"