Paul Rogers
7/9/2007 5:07:00 PM
On Jul 9, 10:25 am, Robert Klemme <shortcut...@googlemail.com> wrote:
> On 09.07.2007 17:41, Paul Rogers wrote:
>
> > Im trying to come up with an easy way to generate a random string,
> > based on a supplied pattern, maybe something like:
>
> > String.from_pattern("\d\d\d@\w{3,5}.com") => "4...@amnf.com"
>
> > Ive used a standard reg exp format here, but it doesnt matter if it
> > uses something else.
> > Any simple way to do this?
>
> Dunno whether you'd count this as simple:
>
> "%d-%d{3}-%w{3,5}".gsub /%(.)(?:\{(\d+)(?:,(\d+))?\})?/ do |m|
> t, mi, ma = $1, $2, $3
>
> rep = case
> when mi.nil?
> 1
> when ma.nil?
> mi.to_i
> else
> mi.to_i + rand(1 + ma.to_i - mi.to_i)
> end
>
> case t
> when "d"
> rep.to_enum(:times).inject("") {|s,| s << (?0 + rand(10)).chr}
> when "w"
> rep.to_enum(:times).inject("") {|s,| s << (?a + rand(1 + ?z -
> ?a)).chr}
> else
> # ignore
> m
> end
> end
>
> Kind regards
>
> robert
its more elegant than I had, not sure about simpler ;-)
I had to do this ( just in case any one else tries it )
require 'enumerator'
Thanks!
Paul