From: Robert Klemme Date: 2007-07-11T22:18:58+09:00 Subject: Re: create a string from a pattern? 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") => "412@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