Class Methods types

suggest change

Classes have 3 types of methods: instance, singleton and class methods.

Instance Methods

These are methods that can be called from an instance of the class.

class Thing
  def somemethod
    puts "something"
  end
end

foo = Thing.new # create an instance of the class
foo.somemethod # => something

Class Method

These are static methods, i.e, they can be invoked on the class, and not on an instantiation of that class.

class Thing
  def Thing.hello(name)
    puts "Hello, #{name}!"
  end
end

It is equivalent to use self in place of the class name. The following code is equivalent to the code above:

class Thing
  def self.hello(name)
    puts "Hello, #{name}!"
  end
end

Invoke the method by writing

Thing.hello("John Doe")  # prints: "Hello, John Doe!"

Singleton Methods

These are only available to specific instances of the class, but not to all.

# create an empty class
class Thing
end

# two instances of the class
thing1 = Thing.new
thing2 = Thing.new

# create a singleton method
def thing1.makestuff
  puts "I belong to thing one"
end

thing1.makestuff # => prints: I belong to thing one
thing2.makestuff # NoMethodError: undefined method `makestuff' for #<Thing>

Both the singleton and class methods are called eigenclasses. Basically, what ruby does is to create an anonymous class that holds such methods so that it won’t interfere with the instances that are created.

Another way of doing this is by the class << constructor. For example:

# a class method (same as the above example)
class Thing
  class << self # the anonymous class
    def hello(name)
      puts "Hello, #{name}!"
    end
  end
end

Thing.hello("sarah") # => Hello, sarah!

# singleton method

class Thing
end

thing1 = Thing.new

class << thing1
  def makestuff
    puts "I belong to thing one"
  end
end

thing1.makestuff # => prints: "I belong to thing one"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents