简体   繁体   中英

Ruby exits my each loop when an if-statement inside is false

Why does code below exit the each loop as soon as the if-statement "g2k.has_key?(k)" is false

  e.element_children.all? do |n|
    k = n.name.to_sym
    logger.info("#{n.name} as symbol is '#{k}' is valid? = #{g2k.has_key?(k)}")
    if g2k.has_key?(k)
      logger.info("#{g2k[k] }= #{n.content}")
    #  @vehicle_data[g2k[k]] = n.content
    end
  end

This loops through all element children as intended

  e.element_children.all? do |n|
    k = n.name.to_sym
    logger.info("#{n.name} as symbol is '#{k}' is valid? = #{g2k.has_key?(k)}")
    #if g2k.has_key?(k)
    #  logger.info("#{g2k[k] }= #{n.content}")
    #  @vehicle_data[g2k[k]] = n.content
    #end
  end

I'm using rails 3.2 with Ruy 1.9, parsing XML with nokogiri.

Once all? finds something false, then it can't be all, so it's going to stop processing.

Here's an example: http://rubyfiddle.com/riddles/cb777 --- you'll see that it stops after printing 5 because 5 is not < 5

(1..20).all? do |i|
  puts i
  i < 5
end

# prints:
1 
2 
3 
4 
5

Unless you are capturing the output of the .all? method you should not be using it. .all? is used to make sure every element in an array returns true. .each will just iterate over all of them. .detect will iterate until true is returned.

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