Defining a Class and Instantiating an Object
You’re probably familiar with creating objects in PHP. But here’s just a quick refresher. First things first, we need a class that defines our object.
Let’s create a new PHP file called Cat.php
and define our class in it:
Note: I went ahead and assumed you know to add <?php
at the top of the Cat.php
file before our definition, because that’s what we PHP developers do.
Now that we have a Cat class, we can create Cat
objects. Below our definition of the Cat
class let’s instainiate a new cat:
But you knew all of that. Alright, time for you to create your first Ruby class. It’s a pretty big moment.
First things first, we need to create a file to store your class in. Create a new Ruby file called cat.rb
.
Now we can define our Cat
class inside of cat.rb
:
class Cat
def meow
puts 'meow'
end
end
Sorry to let you down if you were looking for something more complex. But it’s really that simple.
Now let’s instantiate our first Ruby object. The only real difference here is that the Class itself has a new
method. Also some backstory, our cat’s name is Momma and because this is my book I’ll be giving her a cameo.
momma = Cat.new
momma.meow
=> 'meow'
It’s exactly the same amount of lines as PHP, but instead of instantiating with new Cat
as we’re used to - instead we call the new
method on the Cat
class itself; i.e. Cat.new
. This is a small detail for now, but it’s implications are huge.