02
Yeah, yeah, OK, I can't name blog post titles very creatively :)
This is simply a repost of a blog post I did a few months ago, but I'm not sure many people here have read my other more generalized blog, so I'll repost the Groovyish content here now and then.
Someone recently asked how to get a random element from an array. In PHP it’s pretty straightforward - array_rand($x) - but there’s not (AFAICT) a built-in way in Groovy to do this. So I wrote a little something which should hopefully demonstrate the power of the metaClass stuff to boot.
ArrayList.metaClass.getRand = { number -> if(number==0) { return delegate[new Random().nextInt(delegate.size)] } else { def tempList = [] def counter = 0 while(counter>number) { tempList.add(delegate[new Random().nextInt(delegate.size)]) counter } return tempList } } def names = ['mike','matt','mark','lesley','jean','ron','jeff','martine'] println names.getRand() println names.getRand(5)
The first call to getRand() on the names list will just return one name from the list. The second will return 5 random entries (and some could theoretically be repeated). I’ve added this getRand() method to the base ArrayList class at runtime, even though it’s likely declared ‘final’ in Java’s base libraries. This is one of the core powers of Groovy, and is pretty slick, imo.





