create a string from a pattern?

P

Paul Rogers

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") => "(e-mail address removed)"

Ive used a standard reg exp format here, but it doesnt matter if it
uses something else.
Any simple way to do this?

Thanks
Paul
 
R

Robert Klemme

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") => "(e-mail address removed)"

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
 
P

Paul Rogers

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,311
Members
47,983
Latest member
Derek9890

Latest Threads

Top