-1

In Rails Models, I've seen what I'm assuming are called class methods defined either by

def methodName
   #do something
end

and

def self.methodName
   #do something
end

I can't seem to find anywhere that gives a description of the differences between these two, and when you should use one vs the other.

Also not sure if this is specific to Ruby, Rails or other languages as well. Thanks

pedalpete
  • 21,076
  • 45
  • 128
  • 239

3 Answers3

4

Assuming User model

  1. Instance methods

     def methodName
    
        #do something
     end
    

to call this method use

User.new.methodName
  1. Class Methods

    def self.methodName #OR User.methodName
      #do something
    end
    

to call this method use

User.methodName
Salil
  • 46,566
  • 21
  • 122
  • 156
3

The first one is an instance method, the second one is a class method. You can find more info here

Lyuben
  • 31
  • 1
1

Not both are class methods.

def methodName is an instance method, while def self.methodName is a class method.

The difference between both can be explained like in the example below.

class MyClass
  def instance_method_name
  end

  def self.class_method_name
  end
end


MyClass.class_method_name
MyClass.new.instance_method_name
Arjan
  • 6,264
  • 2
  • 26
  • 42
  • There is no such thing as "class method" in Ruby. Your `class_method` is an instance method just like any other instance method, in particular, it's an instance method of `MyClass`'s singleton class. – Jörg W Mittag Aug 09 '13 at 11:46
  • The rubydoc disagrees with you. http://www.ruby-doc.org/core-1.9.3/Class.html – Arjan Aug 09 '13 at 11:54