DBC-Technical Blog:
Date: 08.16.15
Entry #: 6
Commentary:
Class Methods: I wanted to give a small tutorial on Ruby Class Methods today. This is one of the simplest concepts to grasp an anybody can learn them with a few short keystrokes. First, lets familiarize the syntax!
def run()
p "Have a nice run today!"
end
run()
In the above example, we've demonstrated the syntax on how to create a class method and how to call on it. First, we ALWAYS start with a 'def' and end with an 'end'. The code that appears between these two operators consists of printing, (visible to the user-end) a string, (a sentence encapsulated by quotation marks) that reads 'Have a nice run today!'. Now, once we created the method, in order for this method to run, the computer must be told to run it by calling on the method (hence why we've written run after the last 'end').
Now that we have the syntax spelled out, let take a deeper look into what is actually happening. Think of methods as actions, verbs per say. In the above example, we created a 'run' method that performs an action and what is coded within the method is what we want to happen when this action is called upon. If one were to copy/paste this code into a text editor of their choice, and ran it through the terminal it would output "Have a nice run today!". THis is the general gist of how methods work and their syntax, albeit seeming very straight forward, their power and complexity can become far more powerful by adding arguments -(which would be contained in the empty parenthesis next to 'run'), instance variables, etc.