Dynamically Creating Methods from Strings
suggest changeRuby offers define_method
as a private method on modules and classes for defining new instance methods. However, the ‘body’ of the method must be a Proc
or another existing method.
One way to create a method from raw string data is to use eval
to create a Proc from the code:
xml = <<ENDXML
<methods>
<method name="go">puts "I'm going!"</method>
<method name="stop">7*6</method>
</methods>
ENDXML
class Foo
def self.add_method(name,code)
body = eval( "Proc.new{ #{code} }" )
define_method(name,body)
end
end
require 'nokogiri' # gem install nokogiri
doc = Nokogiri.XML(xml)
doc.xpath('//method').each do |meth|
Foo.add_method( meth['name'], meth.text )
end
f = Foo.new
p Foo.instance_methods(false) #=> [:go, :stop]
p f.public_methods(false) #=> [:go, :stop]
f.go #=> "I'm going!"
p f.stop #=> 42
Found a mistake? Have a question or improvement idea?
Let me know.
Dynamically Creating Methods from Strings
Table Of Contents
3 Arrays
4 Classes
5 Hashes
9 Strings
10 Symbols
11 Exceptions
12 Thread
13 Methods
15 Numbers
16 Iteration
18 Comparable
19 Gem usage
22 Range
23 Comments
24 Operators
25 Operators
27 Modules
30 Constants
32 rbenv
34 Singletons
35 File I/O
36 Time
37 Queue
39 IRB
40 Enumerators
41 C extensions
42 Struct
48 DateTime
49 Truthiness
55 Refinements
59 Debugging
61 Recursion
62 Installation
63 ERB
67 OptionParser
70 Enumerable
73 Contributors