tags:

views:

84

answers:

3
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?

+7  A: 

Use a Mixin.

module AdditionalMethods
  def new_method
    "do some things"
  end
end

obj = SomeObject.new
obj.extend(AdditionalMethods)

puts obj.new_method
> "do some things"
Rinzi
+1  A: 

You can use modules.

module ObjSingletonMethods
  def new_method
    "do some things"
  end
end


obj.extend ObjSingletonMethods

puts obj.new_method # => do some things

Now if you need to add more methods to that object, you just need to implement the methods in the module and you are done.

Chirantan
A: 

Just an interesting point to note:

if you had instead gone:

def my_method
    def my_other_method; end
end

Then my_other_method would actually be defined on the CLASS of the object not withstanding that the receiver ofmy_method is an instance.

However if you go (as you did):

def my_method
    def self.my_other_method; end
end

Then my_other_method is defined on the eigenclass of the instance.

Not directly relevant to your question but kind of interesting nonetheless ;)

banister