The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Hashes with default procs as memoized functions

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Eigen Class

Posts: 358
Nickname: eigenclass
Registered: Oct, 2005

Eigenclass is a hardcore Ruby blog.
Hashes with default procs as memoized functions Posted: Dec 28, 2005 4:05 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Eigen Class.
Original Post: Hashes with default procs as memoized functions
Feed Title: Eigenclass
Feed URL: http://feeds.feedburner.com/eigenclass
Feed Description: Ruby stuff --- trying to stay away from triviality.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Eigen Class
Latest Posts From Eigenclass

Advertisement

Thinking of optimizing the small script I wrote long ago to analyze the geographical distribution of eigenclass' readership, I bumped into yet another instance of the "hash with default block as memoized function" idiom. I've been finding that quite often when reviewing older code of mine (or at least feel that way).

That script uses GeoIP's command-line utility to determine which country an IP address is associated to. Calling an external program is really slow so I absolutely want to cache those results:

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 {}

One minor inconvenience about hashes with default procs is that they cannot be serialized, so it would seem one needs something like

File.open("geo.cache", "w"){|f| Marshal.dump(Hash[*iptocountry.to_a.flatten], f)}

We can do much better though:

iptocountry.default = nil
File.open("geo.cache", "w"){|f| Marshal.dump(iptocountry, f)}

Hash#default= will override the default specified in the Hash.new call.


Read more...

Read: Hashes with default procs as memoized functions

Topic: SwitchTower wishlist Previous Topic   Next Topic Topic: Massive Scalability and Fast Cars


Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2018 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use