I have altered your code a little:
Code:
require 'open-uri'
require 'rss/2.0'
def get_feed_entries(address, total_entries = 5)
open(address) do |feed|
channel = RSS::Parser.parse(feed.read, false).channel
items = channel.items[0...total_entries]
items.map do |item|
item.title.strip
end
end
end
feeds = [
'http://www.1lotus.com/rss/2.0/journal_all.xml',
'http://feeds.feedburner.com/hicksdesign/']
for url in feeds
feed = get_feed_entries(url)
feed.each_with_index do |entry, i|
puts "#{i + 1}. #{entry}"
end
puts
end
Let me explain:
line 1: open-uri is a standard Ruby library that lets you open a document on the web with the function open(url). This way you don't have to do magic with regexes to get the right format for the url (open can figure everything out).
line 4: I used a function instead of a class because it is very simple, and a class with one menthod doesn't make sense. You can always wrap it in a class if you need more functionality. But I prefer an approach that uses functions because it is often simpler. I also gave total_entries a default value, so we can omit it in most calls.
line 5: Here you see the call to open. It also uses a block which will be called with the downloaded result.
line 6: Parse the feed and extract the channel
line 7: the items[0...total_entries] removes all entries beyond total_entries. I used three dots because we want 5 entries. If there were 2 dots, Ruby would extract the first 6 entries.
line 8 + 9: If you ever want to take an array, do something with the items in it, and put the result in an array, map is your friend, because it does it for you. It "maps" all items to item.title.strip, and returns the result (so it does not modify the original, if you want that, use map!). Note that we don't need an explicit return statement, because the last thing in a function will be returned automatically.
line 14..16: I use literal notation for arrays. It is more convenient than foo = Array.new; foo[0] = ...; foo[1] = ...;
line 18..23: Nothing special here.
line 25: if you call puts without arguments, it prints a newline. (so you don't need "\n")
If you have any questions, please ask!
Bookmarks