Break in a each function


#1

i have a method , and i only want the first 10 feeds to be put in the
database , why doesn’t this control structure works , when the counter
is 10 it has to jump out the iteration

greetz Klaas

def get_feed2(rssfile)
# Open the RSS file
rssfeed = open(rssfile.url)
# Use the built-in REXML module

		 # Read the entire RSS file into memory
		 rssdoc = Document.new rssfeed.read
		 #Extract some header data about the feed
		 title = rssdoc.elements['rss/channel/title'].text
		 link = rssdoc.elements['rss/channel/link'].text
		 counter = 0
		 # Extract each RSS item

	rssdoc.elements.each('rss/channel/item') do |item|
		counter = counter + 1
		@artikel=Article.new
		@artikel.titel = item.elements['title'].text
		@artikel.bronvermelding = item.elements['link'].text
		@artikel.article_type_id = 1
		@artikel.publicatie_on = Time.new
		paragraaf = Paragraaf.new()
		paragraaf.ondertitel = item.elements['title'].text
		paragraaf.tekst =  item.elements['description'].text
		@artikel.bericht = paragraaf.to_html
		@artikel.save
		next unless counter===10
	end

end

#2

klaas wrote:

i have a method , and i only want the first 10 feeds to be put in the
database , why doesn’t this control structure works , when the counter
is 10 it has to jump out the iteration

Because you don’t actually tell the loop to “break”. Using a conditional
next at the bottom of a loop doesn’t imply a break when the test fails.
It simply skips the next line. And even when it doesn’t the next doesn’t
do anything because the loop would continue anyway, as long as there are
more elements to iterate over.

  	@artikel.bericht = paragraaf.to_html
  	@artikel.save
  	next unless counter===10
  end

Change the next line to:

 break if counter == 10

And you’ll get the result you are looking for.

-Brian