Ruby self and method definitions

ruby, self

Solution

This is explained in a nice article by ruby-core contributor yugui: Three implicit contexts in Ruby. Basically, there is a default definition context, which is not the same as `self`. Methods that are not explicitly defined as singleton methods end up as instance methods of the default definition context. `module` and `class` definition bodies change the default definition context whereas `def` doesn't. `instance_eval` OTOH does change it.

Problem

``` class MyClass def one def two end end end obj = MyClass.new obj.one puts obj.method(:two).owner #==> MyClass ``` Here i define method two inside another method one. Method one is called by the instance of MyClass (obj) . So the self is obj when the method two is defined. when i check the owner of method two it's MyClass ``` obj.instance_eval do def three end end puts obj.method(:three).owner #==> #<Class:#<MyClass:0x007f85db109010>> ``` In this snippet i do instance_eval on obj , so the self is again obj when the method three is defined . But when i check the owner of three , it's the singleton class of obj why is this? is there anything else besides self which determines where the method definition goes ??

Original source