Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm learning ruby and ROR at the same time and noticed one thing in someone else's code. Sometimes I see methods being defined in these two apparently slightly different ways:

class SomeClass < SomeInheritance::Base

  def self.myMethod
  end

  def myOtherMethod
  end

end

Does it make any difference? I mean, does the use of self in a method definition affects the way the method works somehow? Any enlightenment is welcome.

like image 732
marcio Avatar asked Dec 16 '11 18:12

marcio


2 Answers

def self.method_name will define a class method rather than an instance method - as will

class << self; def foo; end; end

A good post on the topic is this post from Yehuda Katz

for example:

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>
like image 101
klochner Avatar answered Oct 20 '22 22:10

klochner


If you try this code:

class SomeClass
  p self
end

you will get 'SomeClass' printed. That's because self refers to the SomeClass object (yes, clases are objects in Ruby too).

With self, you can define a class_method, i.e. a method on the class object (although it's actually defined in the object's metaclass...):

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

There's much more to know about Ruby object model. Dave Thomas gave an excellent talk on this subject - see the link @Octopus-Paul recommended to you.

like image 22
Marek Příhoda Avatar answered Oct 20 '22 21:10

Marek Příhoda