Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In how many ways can methods be added to a ruby object?

When it comes to run time introspection and dynamic code generation I don't think ruby has any rivals except possibly for some lisp dialects. The other day I was doing some code exercise to explore ruby's dynamic facilities and I started to wonder about ways of adding methods to existing objects. Here are 3 ways I could think of:

obj = Object.new

# add a method directly
def obj.new_method
  ...
end

# add a method indirectly with the singleton class
class << obj
  def new_method
    ...
  end
end

# add a method by opening up the class
obj.class.class_eval do
  def new_method
    ...
  end
end

This is just the tip of the iceberg because I still haven't explored various combinations of instance_eval, module_eval and define_method. Is there an online/offline resource where I can find out more about such dynamic tricks?

like image 786
David K. Avatar asked Jun 13 '11 06:06

David K.


1 Answers

Ruby Metaprogramming seems to be a good resource. (And, linked from there, The Book of Ruby.)

like image 175
jtbandes Avatar answered Sep 25 '22 07:09

jtbandes