Cool Ruby Feature: A Hash With a Dynamic Default

Posted: Thu, 3 May 2007 | permalink | No comments

 h = Hash.new { |h,k| k*k }
 
 h[1] = 42
 
 puts "1 => #{h[1]}, 2 => #{h[2]}, 3 => #{h[3]}"

Produces:

 1 => 42, 2 => 4, 3 => 9

It's weird little things like this that make me really love Ruby.


Post a comment

All comments are held for moderation; markdown formatting accepted.

This is a honeypot form. Do not use this form unless you want to get your IP address blacklisted. Use the second form below for comments.
Name: (required)
E-mail: (required, not published)
Website: (optional)
Name: (required)
E-mail: (required, not published)
Website: (optional)