Generating a random string in Groovy
A while ago, I wrote a post about using LINQ in C# to generate a random confirmation number. On my current gig we are using Groovy to write test scripts for SOAP UI acceptance test cases (incidentally, SOAP UI is a great web service testing tool that probably deserves its own blog post).
In order to generate a dummy random string, I used an algorithm similar to the one I used in the LINQ post and wanted to show how it would be implemented in Groovy.
// create the list of available characters
def availChars = []
('A'..'Z').each { availChars << it.toString() }
// even it out to about the same odds of getting a char or a number
3.times { (0..9).each { availChars << it.toString() } }
def generateRandomString = { length ->
def max = availChars.size
def rnd = new Random()
def sb = new StringBuilder()
length.times { sb.append(availChars[rnd.nextInt(max)]) }
sb.toString()
}
// print it out 10 times to see the randomness
10.times { println generateRandomString(8) }
If you're not familiar with Groovy, the -> symbol in the generateRandomString declaration marks a closure that takes one argument. In this case, it takes the desired length of the returned string. The last line invokes the closure n times. I really like (similar to Ruby) how you can pass function blocks as iterators over collections. It makes creating a loop both simple and intuitive (e.g. 10.times). And the syntantical sugar of creating a ranged list (e.g. 'A'..'Z') is another nice feature of the language.
Monday, July 14, 2008 2:21:50 PM (Eastern Standard Time, UTC-05:00)
Groovy