Last Updated: February 25, 2016
·
1.755K
· bitpimpin

Need #define_singleton_method in Ruby 1.8.7?

I recently found myself in need of #define_singleton_method for a project that is still running Ruby 1.8.7—yeah, yeah, I know... But I'm not the only one. Of course, if it is in the context of a Ruby on Rails application, the core team was nice enough to back-port Object#singleton_class for dealing with situations like this. However, outside of a Rails application, you may still need something to get at the singleton class (or metaclass, if you prefer that terminology).

Thankfully, Ruby's open classes allow us to work some magic like so:

class Object
  def singleton_class
    class << self; self; end
  end
end

And, voila! You can now do something like this:

some_object.singleton_class.send :define_method, :method_name { method.body }

Happy coding!

1 Response
Add your response

Hi Mark. What about defining it on modules?

over 1 year ago ·