Static Methods in Ruby
In the PHP ecosystem, static methods were made incredibly popular by the Facades available in the Laravel framework.
Facades allow developers to easily interact with many subsystems working together - with one call:
What are Static Methods anyway?
Static methods is just a fancy term for saying that this method is callable without instantiating an object of the class.
Let’s turn back to our Cat class. What if we could just have it meow()
without actually instantiating a new Cat? We could save ourselves a line of code:
These kinds of methods are useful with you have functionality that doesn’t need context of $this
.
If you have a class that doesn’t have a constructor and the methods are all public, you can get away with calling them statically.
How to Create Static Methods in Ruby
So we know that static methods are just methods that don’t require an object to be instantiated to call them.
They’re methods defined at the class level.
What in PHP we call Static Methods, Ruby calls Class Methods.
Ruby doesn’t have a static
keyword that denotes that a particular method belongs to the class level.
Instead we attach the method to the class itself:
class Cat
def self.meow
puts 'meow'
end
end
Cat.meow
=> 'meow'
This notation is confusing at first. However it starts to make sense when you realize that even classes are objects in Ruby. Remember how I told you everything is an object in Ruby? Yea, it’s pretty true.
So the self
variable inside of a class references the class itself. This is why we use instance variables prefixed with the @
symbol for storing varibles in a particular object.