Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add method to an instanced object

Tags:

ruby

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?

like image 716
vise Avatar asked Dec 11 '09 12:12

vise


People also ask

What does the __ Add__ method do?

The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1. __add__(obj2). This works, because int implements the __add__() method behind the scenes.

Is it possible to add a method to an object after creation?

Yes, it is possible - But not recommended Don't do it. Here's a couple of reasons: You'll add a bound object to every instance you do this to. If you do this a lot, you'll probably waste a lot of memory.

How do I add a method to an existing class in Python?

The normal way to add functionality (methods) to a class in Python is to define functions in the class body. There are many other ways to accomplish this that can be useful in different situations. The method can also be defined outside the scope of the class.

What is the __ str __ method in Python?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.


1 Answers

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 
like image 171
vise Avatar answered Nov 05 '22 03:11

vise