Getting started
Casting type conversions
Arrays
Classes
Hashes
Blocks and procs and lambdas
Inheritance
Control flow
Strings
Symbols
Exceptions
Thread
Methods
Method missing
Numbers
Iteration
Regular Expressions and regex based operations
Comparable
Gem usage
Design patterns and idioms
Loading source files
Range
Comments
Operators
Operators
Special constants in Ruby
Modules
Ruby version manager
Gem creation / management
Constants
Variable scope and visibility
rbenv
Environment variables
Singletons
File I/O
Time
Queue
Destructuring
IRB
Enumerators
C extensions
Struct
Metaprogramming
Dynamic evaluation
Dynamic Evaluation
Evaluating a String
Evaluating Inside a Binding
Instance evaluation
Dynamically Creating Methods from Strings
instance eval
Message passing
Keyword arguments
DateTime
Truthiness
JSON with Ruby
Implicit receives, understanding
Monkey patching
Introspection
Monkey patching
Refinements
Monkey patching in Ruby
Catching exceptions with begin rescue
Command line apps
Debugging
Pure RSpec JSON API testing
Recursion
Installation
ERB
Introspection
Random numbers
Getting started with Hanami
OptionParser
Splat operator
Multidimensional Arrays
Enumerable
Ruby access modifiers
Operating system or shell commands
Contributors

Dynamically Creating Methods from Strings

suggest change

Ruby 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents