Ruby Classes For Dummies

It follows a blueprint, behaves in predictable ways and has a specific set of methods we can call on it.

One hundred and seventy-two methods to be exact, the “methods” method being oneIf you’re new to Ruby, you might also be familiar with the array and hash classes.

Which, just like strings, follow their own blueprints and have their own sets of methods:Which bring us nicely on to a very fundamental point about ruby being an object-oriented programming language —We can define our own classes, that will follow blueprints, behave in predictable ways and will have methods we can call, just like strings, arrays and hashes!Let’s say we have a program where we’ll need access to a lot of cats.

Every time we needed a cat, it wouldn’t be enough to to simply assign a new cat to a string.

We’d quickly lose track of your cats and what they can do.

Plus, these strings would be missing the very essence of what it means to *be* a cat.

This is where are classes come in.

We set up our new Cat classes like this:class Catend It’s that’s simple, we’re now ready to start making new catsSo we have Dinah, our brand new cat.

Which is great and all, but poor Dinah can’t do very much yet.

Just like the methods we can call on strings or arrays, it’s time to define some methods we can call on our cats.

First things first; a cat needs a name.

In order to give our cat a name, we’ll need to define some methods.

Great!.We’ve defined our methods so its time to give dinah a name.

Side note: don’t worry *too* about the @’s just yet, they’ll make more sense once you get more familiar with class methods.

So how can we check that Dinah has a name?.We can call the name method we’ve defined.

Our class is starting to take shape.

Now that our cat has a name, it’s time to give her a voice.

How do we do that?.Another method!And lastly, we’ll define a method to check if our cat is hungry:Ok, our cat can now speak, and tell us she’s hungry.

But, if you remember from earlier, we said we wanted a program with lots of cats.

Well, now we have our cat class, which is our blueprint, we can start making them, knowing they’ll behave predictably.

Great!.We now have out cat class that acts as a blueprint, behaves in predictable ways and and has specific methods we can call, just like our string and array classes!For more reading on classes in ruby be sure to check out the Ruby docs:https://ruby-doc.

org/core-2.

2.

0/Class.

html.

. More details

Leave a Reply