In Ruby, a class method is a method declared in a class, that's:
- Created by adding "
self
" (or the class name) before the method name; - Callable without creating an instance of the class;
- Able to access/modify class variables;
- Not able to access class instance variables or instance methods.
#Created by Adding "self
" (or the Class Name) Before the Method Name
To create a class method, you can add "self.
" before the method name, for example, like so:
class Foo
def self.bar
# ...
end
end
Alternatively, you may use the class name to instead of self
, to create a class method:
class Foo
def Foo.bar
# ...
end
end
#Callable Without Creating an Instance of the Class
Class methods are static (i.e. methods are attached to the class itself). Therefore, they can be called on the class itself, without having to create an instance of the class:
class Foo
def self.bar
"bar"
end
end
puts Foo.bar #=> "bar"
If you try calling this method on an instance of the class, it will raise an error:
foo = Foo.new
# undefined method `bar` for #<Foo:0x000055e734934d08> (NoMethodError)
puts foo.bar
#Able to Access/Modify Class Variables
You may access class variables inside a class method:
class Foo
@@baz = "baz"
def self.bar
@@baz
end
end
puts Foo.bar #=> "baz"
Similarly, a class method may modify values of class variables:
class Foo
@@separator = ","
def self.separator=(val)
@@separator = val
end
def self.separator
@@separator
end
end
puts Foo.separator #=> ","
Foo.separator = "|"
puts Foo.separator #=> "|"
#Not Able to Access Class Instance Variables or Instance Methods
A class method does not have access to class instance variables (as they're only relevant to individual class instances). Therefore, if you try to access them in a class method, it will always be nil
(because instance variables are always nil
before initialization):
class Foo
def initialize()
@name = "foo"
end
def self.bar
@name
end
end
puts Foo.bar #=> nil
When you try to access a class instance method from a class method, it will raise an error:
class Foo
def baz
@name
end
def self.bar
baz
end
end
# undefined local variable or method `baz` for Foo:Class (NameError)
puts Foo.bar
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.