This post originated from an RSS feed registered with Ruby Buzz
by Red Handed.
Original Post: Using Hashes to Memoize
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
Whoa, here’s a meme I totally overlooked a month ago. But Mauricio’s brought it back for us with his log parsing script. Originally, the idea was just to use Hashes to cache method results. But Mauricio’s combined it with Marshal so you can cache memoization on disk!
His example is perfect:
iptocountry = Hash.new do |h,ip|
h[ip] = `geoiplookup #{ip}`.chomp.gsub(/^GeoIP Country Edition: /,"")
end
iptocountry.update Marshal.load(File.read("geo.cache")) rescue nil
The iptocountry hash pairs up IP address and their geographic location. Presumably, many of Mauricio’s visitors return often, so this saves his computer a lot of exhaustion. He saves old pairs in geo.cache and if he ever asks the Hash for an IP that hasn’t been looked up, it goes to the shell command to lookup the location. Brilliant!
As I was saying, this idea has been building. MenTaL talked about using Hash.new (definitely read it, it’s very simple!) and Doug Landauer expanded into how to use Hash.new to memoize the Fibonacci series. This is going to replace Ajax in 2006.