From: Chad Perrin Date: 2011-05-11T06:19:49+09:00 Subject: Re: Generate random string matching specific pattern and length --gKMricLos+KVdGMg Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, May 11, 2011 at 05:56:02AM +0900, Kevin wrote: > I'm trying to generate a random set of strings to fill a database with th= at > match the following pattern: /^([A-Z]|[a-z]|-)+$/ >=20 > 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 > 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-strin= gs >=20 > I'm guessing that something like map { if /^([A-Z]|[a-z]|-)+$/ & > char.len=3D=3D10 > strings<< current_matching_value > } >=20 > would achieve the right solution. Any pointers would be greatly > appreciated. There's probably something like a thousand ways to achieve that. By th eway, it looks like you missed a character class -- numbers. Your regex should probably have been something like this: /^([A-Z]|[a-z]|\d|-)+$/ In fact, if it should be exactly ten characters long, you might want that regex to look like this: /^([A-Z]|[a-z]|\d|-){10}$/ If you want to create strings that contain random distributions of characters from a list of possible characters, you could use an array: foo =3D ( ('A'..'Z').to_a << ('a'..'z').to_a << ('0'..'9').to_a << '-' ).flatten bar =3D String.new 10.times { bar << foo.shuffle[0] } Now . . . if you specifically want dashes at specific places in your string (which I suspect you might), that changes things. --=20 Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ] --gKMricLos+KVdGMg Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.14 (FreeBSD) iEYEARECAAYFAk3JqMMACgkQ9mn/Pj01uKXJxwCgiQWVGTXZf0f6NqPtRj2/edtX OI8AoOaNZCw63WVFcz9xUcB4keP+5oYE =quTI -----END PGP SIGNATURE----- --gKMricLos+KVdGMg--