简体   繁体   中英

Why can't I 'break' out of this Ruby block?

I have this Ruby block:

    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

For some unknown reason to me I can't seem to break out of it? I realise the block is a little weird it's semi-copied from here:

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

Honestly my Ruby is poor but I'm trying to write a little mac app that involves some RSS parsing.

The regex matches and status gets set to "FAILURE" but it doesn't break out the block/loop. Am I doing something obviously wrong?

Cheers,

Adam

you dont need the 'then' in your if block

@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

as a side note, it would be more idiomatic to write this as:

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

when you are dealing with enumerable objects, like arrays it is nice to use the tools built into Ruby.

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

break if status == "FAILURE"请尝试break if status == "FAILURE"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM