Difference between instance_eval and singleton method

The Singleton method is a method that is defined for only one instance.

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

Does instance_eval do the same? Defining a method for a specific instance? What is the difference?

+5
source share
2 answers

Does instance_eval metaprogramming tool do the same thing right? Defining a method for a specific instance?

No. instance_eval has nothing to do with defining methods. It evaluates the block in the context of the receiver. Typically, blocks have a lexical scope, including self , a block that is evaluated using instance_eval , evaluated with self , bound to the message recipient.

 one = Object.new two = Object.new def one.my_eval; yield end instance_variables # => [] one.my_eval { @ivar_one = 1 } one.instance_variables # => [] instance_variables # => [:@ivar_one] two.instance_eval { @ivar_two = 2 } two.instance_variables # => [:@ivar_two] 

So what is the difference?

They are completely unconnected. It really doesn't make sense to ask about the difference between two unrelated things.

+4
source

The # instance_eval object is a method with which you can really define a method for an object.

A singleton class is a "place" where the singleton method defined for an object "lives".

So these are two completely different things.

+5
source

Source: https://habr.com/ru/post/1238472/


All Articles