Is there a possiblilty to dynamically create a method, like this?
Fixnum.create_method(:power) do |a|
self ** a
end
or - perhaps easier:
Fixnum.create_method(‘power’) do |me, a|
me ** a
end
I tried to implement such a create_method, but all I came up with was
a solution using a global array of method objects:
def Object.add_method(name, m)
$methods ||= []
$methods << m
module_eval "def #{name}(*args); $methods[#{$methods.length() - 1}].call(self, *args); end"
end
Fixnum.add_method ‘square_plus’, proc { |me, x|
me * me + x
}
I certainly don’t like this hack.
It would be great to have this if one wants to implement something
along the lines of Perl’s autoloader. In the missing_method method,
one would read in the method one wants to add (or dynamically create it)
and add it to the class.
Oh… an autoloader can be done differently, by having the "method files"
look like
MyClass.meth0.al:
class MyClass
def meth0()
# …
end
end
MyClass.foo.al:
class MyClass
def foo()
# …
end
end
But I’d still like to know how to dynamically create a method with a
dynamically given name. If possible, without such a hackery.
Is that possible?
···
–
[mpg123d] Just playing: …/ayumi hamasaki/a best/01 a song for xx.mp3
Das Erzeugen von C-Code ist sehr fehlerhaft und klappt nur bei ganz
einfachen Programmen. [Alvar Freude in de.comp.lang.perl.misc]