Class Methods types
suggest changeClasses have instance methods and singleton methods. A class method is a singleton method of the class object. The sections below treat those as three cases.
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 # prints: something
Class Method
These are invoked on the class, not on an instance 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 kinds of method live on an eigenclass (also called a singleton class). Ruby creates an anonymous class to hold them so they do not become methods of every instance.
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"
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents