The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Hash with block or Block with hash?

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
Andrew Johnson

Posts: 39
Nickname: jandrew
Registered: Mar, 2004

Simple things ...
Hash with block or Block with hash? Posted: Mar 26, 2004 4:02 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Andrew Johnson.
Original Post: Hash with block or Block with hash?
Feed Title: Simple things ...
Feed URL: http://www.siaris.net/index.cgi/index.rss
Feed Description: On programming, problem solving, and communication.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Andrew Johnson
Latest Posts From Simple things ...

Advertisement
byline: Andrew L. Johnson

Not exactly new, passing blocks to Hash.new has been around for a while (since the 1.8.0 release I think). This can be used to supply a default value or action for accessing keys not in the hash.

  hash = Hash.new {|h,k| h[k] = "Default Value"}

  hash = Hash.new {|h,k| raise "No Such Key #{k}"}

Note, the objects yielded to the block are the hash and the key (not a key and a value, which is an easy but nonsensical mistake to make).

In the first example above we didn’t just return a default value, we also assigned to the appropriate key in the hash — next time we try to access the hash using this key we will get the default value directly instead of having to evaluate the block again. This point of view — a hash with a block attached to generate default values — is useful, but not terribly interesting.

Turning the view around we have a block with an attached cache — giving us simple memoization. Here’s a little memoized factorial calculator:

  fact = Hash.new {|h, n| n < 2 ? h[n] = 1 : h[n] = h[n-1] * n}
  p fact[4]   #--> 24
  p fact      #--> {1=>1, 2=>2, 3=>6, 4=>24}

Now, there are obvious limitations: the [] hash method takes a single object as a key so you can’t pass multiple parameters directly (you’d need to wrap them in an array or something), and, parameter caching will be based on the #hash method of the objects used as keys. Another limitation is cache size and expiry — in which case you might want to try the memoize module available on the RAA.

Read: Hash with block or Block with hash?

Topic: Learn to Program -- A Tutorial for the Future Programmer Previous Topic   Next Topic Topic: Postgres Lib RDocumentation

Sponsored Links



Google
  Web Artima.com   

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