From: Christoph Date: 2002-02-20T02:21:52+09:00 Subject: Re: Anonymous class support wrote in message news:200202190622.g1J6MqX18863@sharui.nakada.kanuma.tochigi.jp... > Hi, > > At Tue, 19 Feb 2002 10:33:31 +0900, > David Corbin wrote: > > I find Java anonymous classes to be very helpful when writing UnitTests, > > because I can overide a method for "one time use" just to verify it gets > > called correctly. > > > > I realize that I can write a new class that responds to whatever methods > > I need. But I'm talking about the syntactic convenience of defining > > the method as part of the the new call. > > > > Does Ruby have support for anything like this? > > As written already, you can use blocks, singleton methods, and > anonymous class with Class.new like: > > Class.new(superclass).class_eval do > def foo > end > end > > In 1.7, .class_eval isn't necessary. Unfortunately you cannot use the ladder idiom within method bodies - for example .. ---- class A def foo(&body) Class.new(type,&body) end def goo(&body) res = Class.new(type) res.class_eval &body # this works because &body is a string! res end # end anon =A.new.foo { Pointless = "okay" } puts anon.const_get :Pointless # => okay # A.new.foo { def annoying_parse_error() end } anon.new.goo { def okay(); puts "okay" end }.new.okay # => okay ---- I was swearing to myself more than once about the latter parse error - i.e. Matz would make my day | week if he would do away with it in most situations ... /Christoph