Forum: Ruby on Rails break in a each function

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7007cea0aa8f62646493ac4b50ae0641?d=identicon&s=25 klaas (Guest)
on 2006-03-01 11:34
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
7c4087d053eb02d099a17d91ba5e33b5?d=identicon&s=25 Brian V. Hughes (Guest)
on 2006-03-01 15:39
(Received via mailing list)
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
This topic is locked and can not be replied to.