On 2/9/07, Carl Lerche <carl.lerche / gmail.com> wrote:
> Hello,
>
> I'm just curious what your favorite bit of ruby code is? Do you have
> any small bits, methods, classes, or anything else, that just make you
> say "Wow, that is sweet!"
>
> I'd like to see some of them!
>

# I clearly remember this thing making me smile as I wrote it
# of course, it's imperfect, as is everything.
class LSystem
	attr_reader :output

	def initialize( in_axiom, in_rules, in_iterations = 0 )
		@axiom = in_axiom
		@output = in_axiom
		@rules = in_rules
		
		in_iterations.times do iterate end

		return @output
	end
	
	def iterate
		temp_string = ""
		@output.scan( /./ ) do |letter|
			rule_hit = false
			@rules.each do |rule|
				if( letter[ rule[0] ] )
					rule_hit = true
					temp_string << rule[1]
				end
			end
			if( not rule_hit )
				temp_string << letter
			end
		end
		@output = temp_string
	end
end

## Example usage:
require 'LSystem'

the_rules = [
	[ /F/, "" ],
	[ /Y/, "+FX--FY+" ],
	[ /X/, "-FX++FY-" ]
]

the_system = LSystem.new( "FX", the_rules, 10 )

p the_system.output

## Of course, the output isn't very useful without a turtle graphics system. ;)

Regards,
-Harold