From: Robert Klemme Date: 2011-05-11T16:11:46+09:00 Subject: Re: Generate random string matching specific pattern and length On Tue, May 10, 2011 at 10:56 PM, Kevin wrote: > I'm trying to generate a random set of strings to fill a database with that > match the following pattern:  /^([A-Z]|[a-z]|-)+$/ > > The array I'm trying to create must contain strings that look like > "A12-34-4567" and be exactly ten characters long I have seen code on the That's 11 characters btw. > internet for generating random strings but I don't have internet at home at > the moment to really study examples like the one here: > http://coderrr.wordpress.com/2008/10/28/ruby-golf-generating-random-strings Just a hint: that does not work on 1.9 because ?a does not return a Fixnum any more. > I'm guessing that something like map { if  /^([A-Z]|[a-z]|-)+$/  & > char.len==10 >  strings<< current_matching_value > } > > would achieve the right solution.  Any pointers would be greatly > appreciated. Often there is not _the_ right solution (-> TIMTOWTDI). So far nobody seems to have suggested good old sprintf: BASE = 'A'.getbyte 0 DELTA = 'Z'.getbyte(0) - BASE 10.times do s = sprintf '%s%02d-%02d-%04d', (BASE + rand(DELTA)).chr, rand(100), rand(100), rand(10000) puts s, s.length end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/