Is there a difference between `def self.myMethod` and` def myMethod`?

I study ruby ​​and ROR at the same time and noticed one in the code of the other. Sometimes I see methods defined by these two, apparently in slightly different ways:

class SomeClass < SomeInheritance::Base def self.myMethod end def myOtherMethod end end 

Does it really matter? I mean, does using the self method in a method definition affect the way the method works? Any enlightenment is welcome.

+6
source share
2 answers

def self.method_name will define the class method, not the instance method - like

class << self; def foo; end; end

Good post on this post by Yehuda Katz

, eg:

 class Foo def method_1 "called from instance" end def self.method_2 "called from class" end class << self def method_3 "also called from class" end end end > Foo.method_1 NoMethodError: undefined method 'method_1' for Foo:Class > Foo.method_2 => "called from class" > Foo.method_3 => "also called from class" > f = Foo.new => #<Foo:0x10dfe3a40> > f.method_1 => "called from instance" > f.method_2 NoMethodError: undefined method 'method_2' for #<Foo:0x10dfe3a40> > f.method_3 NoMethodError: undefined method 'method_3' for #<Foo:0x10dfe3a40> 
+20
source

If you try this code:

 class SomeClass p self end 

you will get "SomeClass". This is because self refers to the SomeClass object (yes, clans are also objects in Ruby).

With self you can define class_method, i.e. method for the class object (although it is actually defined in the metaclass of the object ...):

 class SomeClass def self.class_method puts "I'm a class method" end def instance_method puts "I'm an instance method" end end SomeClass.class_method # I'm a class method 

Learn more about the Ruby object model. Dave Thomas gave an excellent discussion on this subject - see @ Octopus-Paul Link recommended by you.

+1
source

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


All Articles