Search code examples
ruby

Add method to an instanced object


obj = SomeObject.new

def obj.new_method
  "do some things"
end

puts obj.new_method
> "do some things"

This works ok. However, I need to do same thing inside an existing method:

def some_random_method
  def obj.new_method
    "do some things"
  end
end

Works ok as well, but having a method inside a method looks pretty horrible. The question is, is there any alternate way of adding such a method?


Solution

  • In ruby 1.9+, there's a better way of doing this using define_singleton_method, as follows:

    obj = SomeObject.new
    
    obj.define_singleton_method(:new_method) do
      "do some things"
    end