By Peter Cooper / June 14, 2006
The RubyExamples page is a few years old now, but I just came across a great example which still works, and which demonstrates the intense power of Ruby. Please note that Justin Bishop deserves all the credit for this one.
Here’s the routine:
class RubyStock
require ‘net/http’
def RubyStock::getStocks(*symbols)
Hash[*(symbols.collect{|symbol|[symbol,Hash[\\
*(Net::HTTP.get('quote.yahoo.com','/d?f=nl1&s='+symbol).chop\\
.split(',').unshift("Name").insert(2,"Price"))]];}.flatten)];
end
end
Using it is simple:
puts RubyStock::getStocks(“MSFT”, “IBM”, “GOOG”).inspect
=> {“GOOG”=>{“Name”=>”\”GOOGLE\”", “Price”=>”386.525″}, “IBM”=>{“Name”=>”\”INTL BUSINESS MAC\”", “Price”=>”76.93″}, “MSFT”=>{“Name”=>”\”MICROSOFT CP\”", “Price”=>”21.51″}}
Amazing! It returns within half a second on my machine, and I can’t believe the same scraping logic works after three years. Read More