About Classes in Ruby

Phase 0, week 5 - June 13th, 2014

Classes - and methods - are basically chunks of code that can be reused later just by calling their name anywhere in the code, which is a great way to avoid repeting code that is ran often in your app. Classes, themselves, are groups of methods that work together to get a certain output from a previous input.

Once you call a method, you have to pass it the input and, after it runs, you should get the output desired. It could be a number in a different format or a true/false statement confirming that a number or an answer is valid or not, for example.

Methods and classes are great because they are like tools you can build on your own. So let's say we are working on a trivia game and, after every answer the user inputs, the app has to check if the answer is true or not and return a praise or a "try again" message to the user. You wouldn't want to reapeat that code again and again after every question in the game, that just wouldn't be a DRY code.

In this situation, you could create a Check_answer method that will do all the work every time the user answers a question.

Creating a Class

Creating a Class is super easy. You just have to write class and then give it a name. Of course, you have to close it wih an end tag, then the code that is going to be repeated everytime the class is called is going right between those lines, just as shown below.

class TheNameYouLike
... your repeatable code goes here
end

Instance Variables

As you may know, variables inside methods - or local variables - are not accessible from outside themselves. As a class is basically a group os methods, however, you can define instance variables when you need them to be accessible anywhere inside the class, by any of the methods.

Instance variables necessarily need to start with an @ sign.

class TheNameYouLike(input)
def initialize
@num = input # Makes input from class be available to all methods inside it as @num
end

def myMethod1
return @number * 2 # Gets @num - or the class input - and returns it multiplied by two
end
end

The input could be anything - an integer, string, array, hash... - and this is how you feed information into your class so it can do the computations and return your desired output.

Calling a Class

Considering the class created above, you would define a new variable that is going to point at the class, just as shown below.

doubled_value = TheNameYouLike.new(23) # Creates "doubled_value" variable that is pointing to the TheNameYouLike class
double_value.myMethod1 # Applies myMethod1 to double_value

# returns => 46