Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create methods just for the instance of a Ruby class from inside that instance?

Tags:

ruby

Let there be class Example defined as:

class Example   def initialize(test='hey')     self.class.send(:define_method, :say_hello, lambda { test })   end end 

On calling Example.new; Example.new I get a warning: method redefined; discarding old say_hello. This, I conclude, must be because it defines a method in the actual class (which makes sense, from the syntax). And that, of course, would prove disastrous should there be multiple instances of Example with different values in their methods.

Is there a way to create methods just for the instance of a class from inside that instance?

like image 983
Aaron Yodaiken Avatar asked Jun 11 '10 23:06

Aaron Yodaiken


People also ask

Can you call a class method on an instance Ruby?

In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class. We cannot call an instance method on the class itself, and we cannot directly call a class method on an instance.

Can class methods access instance variables Ruby?

class . There are no "static methods" in the C# sense in Ruby because every method is defined on (or inherited into) some instance and invoked on some instance. Accordingly, they can access whatever instance variables happen to be available on the callee.

What is the difference between class method and instance method?

Key TakeawaysInstance methods need a class instance and can access the instance through self . Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls .


1 Answers

You need to grab a reference to the instance's singleton class, the class that holds all the instance specific stuff, and define the method on it. In ruby 1.8, it looks a little messy. (if you find a cleaner solution let me know!)

Ruby 1.8

class Example   def initialize(test='hey')     singleton = class << self; self end     singleton.send :define_method, :say_hello, lambda { test }   end end 

Ruby 1.9 however, provides a much easier way in.

Ruby 1.9

class Example   def initialize(test='hey')     define_singleton_method :say_hello, lambda { test }   end end 
like image 146
thorncp Avatar answered Oct 15 '22 15:10

thorncp