occasionally useful ruby, ubuntu, etc

25Mar/080

Dynamic Methods in Ruby

So this was sort of hard even if it doesn't look like it, but I found out how to do dynamic methods and whatnot. Put this in your class.

def self.my_method(takes, two)
	define_method "cool_"+takes do |arg|
		puts two + arg
	end
end

The "method generator" takes two arguments, and the method itself takes just one. The generator creates a new method that can be called by prefixing whatever the first argument was with cool_, and the generated method prints out the second "method generator" argument followed by whatever the argument to the generated method was.
Output:

>> S.class.my_method "cat", "silly "
=> #<Proc:0xb7639fb8@/home/stuff/file.rb:30>
>> S.cool_cat "goose"
silly goose
=> nil

Not too bad, is it?

Note that "self" is required because instances don't have access to define_method, but the classes do...or something. Anyway, experiment with it a bit ;)

Obviously, this can (and should) be adapted for mixins. Lastly, one could/should replace "S.class" with whatever the class of S is, when typing it in. I was doing this in an attempt to make a custom accessor until I realized I'd spent the last hour generalizing for a case in which there were 3 lines of code.

Filed under: ruby Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.