Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between instance_eval and singleton method

Tags:

ruby

Singleton method is a method that is defined only on one instance.

foo = Foo.new
def foo.case
  #singleton method
end

Doesn't instance_eval do the same thing? Defining a method for a particular instance? What is the difference?

like image 414
mhaseeb Avatar asked Dec 17 '15 05:12

mhaseeb


1 Answers

Object#instance_eval is a method, using which you indeed can define method for an object.

Singleton class is a "place", where the singleton method defined for the object "lives".

So these are two absolutely different things.

like image 141
Andrey Deineko Avatar answered Nov 14 '22 23:11

Andrey Deineko