From: vjoel@... Date: 2001-10-24T07:52:10+09:00 Subject: [ruby-talk:23114] Re: Bruce Eckel's opinion of Ruby Paul Brannan wrote: > module Foo > class Array < Array > def []=(foo, bar) > super(foo, bar) > puts 'foo' > end > end > > def self.foo > a = Array.new > a[0] = 42 > end > > foo > end > > a = Array.new > a[0] = 42 I think I'm going to frame that and put it on my wall! This trick can also be used to dynamically type-check/convert, as a way of emulating parametric types: class Float class Array < Array def []=(i, j) super i, Float(j) end end end af = Float::Array.new af[0] = 1 af[1] = 2.3 af[2] = "1.2e17" p af => [1.0, 2.3, 1.2e+17] af[3] = :foo => TypeError You'd have to override a few other methods, such as <<. But it wouldn't be too hard to automate generating x::Array for x in a list of classes. Since the :: syntax accepts a variable on the left, you can choose the "type parameter" dynamically: x = 3.1 a = x.type::Array.new a << x Heartfelt thanks to the unnamed conference participant who came up with this idea. -- Joel VanderWerf California PATH, UC Berkeley mailto:vjoel@path.berkeley.edu Ph. (510) 231-9446 http://www.path.berkeley.edu FAX (510) 231-9512