On Oct 12, 7:17 am, Ruby Quiz <ja... / grayproductions.net> wrote:
> Usually, you write a regular expression and then search for it in a text string.
> How about doing the opposite? Given a regular expression, generate all of the
> strings that it will match.

I've had no time to implement the actual quiz. (The quiz is very
interesting, though; I hope to find time to tackle it soon.)

However, I thought I'd post a piece of code I wrote for Quiz 48, since
it is related:

class Array
  def random
    self[ rand( self.length ) ]
  end
end

class String
  def variation( values={} )
    out = self.dup
    while out.gsub!( /\(([^())?]+)\)(\?)?/ ){
      ( $2 && ( rand > 0.5 ) ) ? '' : $1.split( '|' ).random
    }; end
    out.gsub!( /:(#{values.keys.join('|')})\b/ ){ values[$1.intern] }
    out.gsub!( /\s{2,}/, ' ' )
    out
  end
end

Used like so:

irb(main):023:0> str = "(lovely|delicious|splendid)(food|snacks|
munchies)"
irb(main):024:0> 10.times{ puts str.variation }
deliciousmunchies
delicioussnacks
splendidsnacks
splendidmunchies
splendidsnacks
deliciousmunchies
lovelysnacks
splendidsnacks
lovelyfood
delicioussnacks

irb(main):025:0> str = "(How (much|many)|What) is (the (value|result)
of)? 6*7?"
irb(main):026:0> 10.times{ puts str.variation }
How many is 6*7?
How much is the value of 6*7?
How much is 6*7?
What is 6*7?
How many is the result of 6*7?
What is the value of 6*7?
What is the value of 6*7?
How many is 6*7?
What is 6*7?
What is 6*7?