I was trying to find a way for generating dynamic methods. My first attempt was very ugly and use a simple eval:
class DynamicMethods
%w{ one two three }.each do |z|
"def #{z}(param) puts 'Hello from \\'#{z}\\' method with \\''+param+'\\' param' end"
eval end
end
Hmm... no... all this escape characters ... there must be a better way. And there is. Using %Q{} ...
class DynamicMethods
%w{ one two three }.each do |z|
%Q{
eval def #{z}(param)
puts "Hello form '#{z}' method with '\#{param}' param"
end
}
end
end
That's better ... more readable, but i don't have syntax highligt for this whole string. Lets try define_method ...
class DynamicMethods
%w{ one two three }.each do |z|
do |param|
define_method z "Hello from '#{z}' method with '#{param}' param"
puts end
end
end
There it is. No eval, no big strings, just a method name and code block. Beautiful. All examples give you same output.
DynamicMethods.new.one("hello") # => Hello from 'one' method with 'hello' param