Ruby: dynamic methods

This takes some getting your head around if you’ve been using statically referenced methods such as in Java or PHP.

Take this class which we’ll save as a file ‘methods.rb’:

class Person

attr_reader :name

def initialize(name)

@name = name

end

def inspect 

“This person’s name is #{@name}”

end

def a_method

puts “I’m a method”

end

end

Now go into irb, load it up and instantiate a new object, e.g.:

load ‘methods.rb’

p = Person.new(“Rafa”)

p.a_method

outputs:

I’m a method

 => nil 

Let’s try a (currently) non-existent method:

p.b_method

which outputs:

defined method `b_method’ for This person’s name is Rafa:Person

from (irb):4

Now here’s the dynamic bit. We can add a new method to the file, save it, load it via irb and those methods are now available to our already-‘compiled’ class. E.g. save this:

class Person

attr_reader :name

def initialize(name)

@name = name

end

def inspect 

“This person’s name is #{@name}”

end

def a_method

puts “I’m a method”

end

def b_method

puts “I’m another method”

end

end

Enter irb, load it and then run this new method:

load ‘methods.rb’

p = Person.new(“Rafa”)

p.b_method

which outputs:

I’m another method

 => nil 

Note: we didn’t create a new object here. We simply loaded the new class into our environment and our existing object dynamically picks up the new method. 

This is just a simple example of how Ruby allows you to add methods in dynamically. Very neat.

Leave a Reply

Your email address will not be published. Required fields are marked *