Ruby Metaprogramming gone wild

Watching the Dave Thomas’ screencasts I’ve learnt a few more interesting ways to use Ruby’s metaprogramming features:

conditional method definition

class Foo
	def a
		def b
		end
	end
end

b will be created only when a is called. This might be useful the correct order of method calling.

methods self replacement

class Foo
	def calculate
		def calculate
			@x
		end
		@x = super_expensive_calculation
	end
end

The first time the method is called it performs some expensive operations and then replaces itself to use a cached value.