# Re: World's simplest code generator in ruby?

**URL:** <https://www.ruby-forum.com/t/re-worlds-simplest-code-generator-in-ruby/68568>\
**Category:** Ruby\
**Created:** [September 13, 2006, 5:39pm UTC](https://www.ruby-forum.com/t/re-worlds-simplest-code-generator-in-ruby/68568 "2006-09-13T17:39:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![phrogz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/2acd7d/32.png) [@phrogz](https://www.ruby-forum.com/u/phrogz)\
**Post date:** [September 13, 2006, 5:39pm UTC](https://www.ruby-forum.com/t/re-worlds-simplest-code-generator-in-ruby/68568/1 "2006-09-13T17:39:42Z")

</div>

From: Mischa K. [[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)]

> There is an .asp application on the internet which calls itself the  
> World’s simplest code generator it can be found here:  
> [(secretGeek.net)](http://secretgeek.net/wscg.asp)

Here’s my hackish implementation in Ruby:

require ‘erb’  
require ‘csv’

data = \<\<ENDDATA  
tim, fruit, veg, he  
sally, whiskey, cigars, she  
jimmy, lager, crisps, he  
jenny, fightin’, cussin’, she  
ENDDATA

pattern = \<\<ENDPATTERN  
$1 loves $2, but $4 hates $3  
%if $2==“whiskey” then  
(Hey $1, i also love $2!!!)  
%end  
ENDPATTERN

# Output all variables that are at the start of the line

template = pattern.gsub( /^$(\d+)/, ‘\<%=line[\1-1]%\>’ )

# Output all variables that are in the middle of a line

while template.gsub!( /^([^%].\*)$(\d+)/, ‘\1\<%=line[\2-1]%\>’ )  
end

# Output all variables left over (in ruby code)

template.gsub!( /$(\d+)/, ‘line[\1-1]’ )

# Create the ERB template

template = ERB.new( template, nil, ‘%’ )

# Clean up the data to be true csv

data.gsub!( /,\s+/, ‘,’ )

# Run the template once for each line

output = “”  
CSV::Reader.parse( data ){ |line|  
output \<\< template.result( binding )  
}

puts output  
#=\> tim loves fruit, but he hates veg  
#=\> sally loves whiskey, but she hates cigars  
#=\> (Hey sally, i also love whiskey!!!)  
#=\> jimmy loves lager, but he hates crisps  
#=\> jenny loves fightin’, but she hates cussin’
