What is a class in Ruby?
Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects.
Objects are the products of the class.
So what is an object?
An object is an individual “thing”, with its own identity & its own data.
Book class could be the blueprint for creating books.
This class defines what attributes ALL books have in common, like:
Every individual book is an object & you can make many objects like it thanks to the
Book class. That’s the point of creating classes, they are reusable blueprints for your Ruby application.
You’re going to learn how to write your own classes so you can start writing OOP code, today.
The syntax for creating a class goes like this:
class Orange end
classkeyword, then the
There are other ways to create a class (like
Class.new), but these methods are only useful in special situations.
The main use of a class is to be a container of methods, instance variables & constants, forming a blueprint which you can create objects from.
You can create objects using the
We know the process of creating an object as “instantiation”, and we say that an object is an “instance” of a class.
Why create objects?
Because every object you create is different & unique.
Every object has its own identity.
Orange class, every
orange object you create has its own weight, country of origin, quality, etc.
Classes become more useful when you start adding instance methods & instance variables to them.
A method is a thing your class can do.
You can squeeze an orange to get juice.
Here’s a code example:
class Orange def squeeze puts "Here's your juice!" end end orange = Orange.new orange.squeeze
These methods become commands for your objects!
Orange object you create will have access to this
squeeze method & that’s one of the benefits of using classes.
An instance variable is something your class knows.
class Orange def initialize @juice_available = 100 end def squeeze @juice_available -= 50 end end
Instance variables are different from local variables because they start with the
@ symbol. You can’t access them outside the class unless you define an attr_accessor.
When working with objects in Ruby it’s helpful to know what class an object is made from.
You can do that like this:
"".class # String .class # Array orange.class # Orange (assuming orange = Orange.new)
Why is this useful?
Methods are the little engines that make things happen in Ruby.
If you know the class you can find out what methods are available (use Google,
pry), in other words, you can discover what the object can do for you!
This is only the “tip of the iceberg” when it comes to classes.
If you want to learn more…
Btw classes themselves are objects too, at least in Ruby 🙂
You have learned about classes in Ruby, how to create them & why they’re useful!
Don’t forget to share this article so more people can enjoy it.
Thanks for reading.