Classes in Ruby are a good way to organize and create a collection of methods that will only work inside that class. We may also make objects that will work for all of these various methods within the same class called instance variables.
To create a class, we start with the keyword ‘class’ followed by the name we want to give our class. This name follows the CamelCase convention, where the first letter of each word is uppercase, and there are no spaces between words. Like methods, when creating a class, it must end with the ‘end’ keyword.
The initialize method allows us to create a new instance of an object in the FavTVShows class. It can also create instance variables (they start with an @ symbol) from the arguments so that we can use them throughout in other methods in the class. We can create a new instance by simply using ‘.new’ along with the right number of arguments needed from the initialize method.
After the initialize method, you will want to create other methods in order to access/change/sort/whatever information about new instances of that class. So for example, I want to be able to access the show’s name, how many seasons there are/were, the starting date, and the end date, as well as a summary of the information given. And if the show hasn’t ended yet, I want it to return “This show has not ended yet.”
The show_title, start_date, and num_of_seasons methods are very simple. They return the value of the corresponding arguments when called. The end_date method and about_show method are a little more complicated. For the end_date method, I used the ternary operator for the if/else statement which says if the argument for end_date is an integer, then it will return the value for end_date. If it not, then it will return a string saying that the show hasn’t ended. For the about_show method, I put in another if/else statement in order to summarize the info about the show. If the end_date is an integer, that means that the show must have ended. Therefore, it will return a string with the end_date. If it’s not a string, then the string will not contain the end_date, and instead say that it’s an ongoing show.
Notice I was able to use the arguments from the new instance in the other methods in the class. This is what is returned when I call each of the methods:
I also set the end_date argument to a string. The reason I did this was to have supernatural.end_date return that string if that argument wasn’t included in the new instance. Notice that for this next example, I don’t put in the argument for end_date.
So both Castle and Supernatural are ongoing shows. So what about a show that has ended?
Because I have created this class, I can add Leverage and Breakout Kings and Lost Girl–I can actually add as many new objects to the FavTVShows class that I want without having to use repetitive and unnecessary code. Pretty cool, huh?