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
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
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.
On Wed, May 11, 2011 at 05:56:02AM +0900, Kevin wrote:
char.len==10
strings<< current_matching_value
}
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 = (
('A'..'Z').to_a << ('a'..'z').to_a << ('0'..'9').to_a << '-'
).flatten
bar = 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.
@Chad: Yes I do need the dashes in the string. I will probably
incorporate your other suggestion with respect to letting the regex
check the overall length as well
@Chris: That definitely looks like it might do the trick. While
writing my original message I had wondered if such a thing existed,
and what do you know, it did.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.