views:

218

answers:

1

I have the following that I retreive the title of each url from an array that contains a list of urls.

require 'rubygems'
require 'nokogiri'
require 'open-uri'

@urls = ["http://google.com", "http://yahoo.com", "http://rubyonrails.org"]

@found_titles = Array.new
@found_titles[0] = Nokogiri::HTML(open("#{@urls[0]}")).search("title").inner_html

#this can go on forever...but
#@found_titles[1] = Nokogiri::HTML(open("#{@urls[1]}")).search("title").inner_html
#@found_titles[2] = Nokogiri::HTML(open("#{@urls[2]}")).search("title").inner_html

puts "#{@found_titles[0]}"

How should i form a loop method for this so i can get the title even when the list in @url array gets longer.

+1  A: 

You're looking for the map (or collect) method:

@found_titles = @urls.map {|url| Nokogiri::HTML(open(url)).search("title").inner_html }
Greg Campbell
Thanks for your prompt help, Greg Campell. This is exactly what I'm looking for.
kim