From: Robert Klemme Date: 2005-09-07T02:06:29+09:00 Subject: Re: ruby style blocks in java Martin Ankerl wrote: > Is there a nice way to implement Ruby-style blocks in Java? I have to > code in Java and I really miss this feature. This is the best thing I > came up with, but it is soooo verbose (untested, just from my head): > > > interface Block { > public Object yield(Object o); > } > > class Array { > public void do(Block b) { > // do something here > while (it.hasNext()) { > Object o = it.next(); > block.yield(o); > } > } > > class Someth > public void doSomething() { > Array a = new Array(); > // do something before > a.do(new Block() { > public void yield(Object o) { > // here is the yield code > } > } > // do something afterwards > } > } That's probably as close as it can get. If you want methods from Enumerable you probably end up writing static methods that receive an Iterator or a Collection and a Block. Not very elegant though. You can also use Groovy - which is quite Ruby like and Java under the hoods. Unfortunately it's significantly slower that pure Java - and maybe also as Ruby. Kind regards robert