Ruby Language Dynamic Evaluation Dynamically Creating Methods from Strings

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


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
  <method name="go">puts "I'm going!"</method>
  <method name="stop">7*6</method>

class Foo
  def self.add_method(name,code)
    body = eval( "{ #{code} }" )

require 'nokogiri' # gem install nokogiri
doc = Nokogiri.XML(xml)
doc.xpath('//method').each do |meth|
  Foo.add_method( meth['name'], meth.text )

f =
p Foo.instance_methods(false)  #=> [:go, :stop]
p f.public_methods(false)      #=> [:go, :stop]
f.go                           #=> "I'm going!"
p f.stop                       #=> 42

Got any Ruby Language Question?