Why Classes?
Why are Clases important in Ruby?
- Classes are a key component of object oriented programming and allow you to be modular and reuse often used methods in a repeatable way without the recreate the methods over and over again. Classes allow you to group functions, variables, and even other classes into one contained object that does not interfere with other objects.
- Classes in Ruby are first-class objects---each is an instance of class Class. Classes are the basic template from which object instances are created.
- A class is a blueprint or template or set of instructions to build a specific type of object. Every object is built from a class. Each class should be designed and programmed to accomplish one, and only one, thing.
- In summary, Ruby classes and Ruby objects are the foundation and building blocks of the programming language and you must learn how to create them in order to create a program based on Ruby.
Important Concepts and Definitions within Classes
- Instance Variables - Instance variables are created for each class instance and are accessible only within that instance. They are accessed using the @ operator. Outside of the class definition, the value of an instance variable can only be read or modified via that instance's public methods.
- Class Methods - Class methods are declared the same way as normal methods, except that they are prefixed by self, or the class name, followed by a period. These methods are executed at the Class level and may be called without an object instance. They cannot access instance variables but do have access to class variables. By default, all methods in Ruby classes are public - accessible by anyone. Here are the different types of methods
- Public method can be accessed from anywhere
- Private method can only be accessed within the class itself. A private method cannot be called outside class scope.
- Protected method can be accessed within the same file and subclasses.
- Instantiation - An object instance is created from a class through the a process called instantiation. In Ruby this takes place through the Class method new.
What are the benefits using Classes?
- Classes are useful to use when you want to give methods to your data or have multiple instances of your data. Classes provide efficiency and reusability
- Classes allow you to reuse commonly used code. They save you the trouble of having to rewrite (and overwrite!) all those lines of code that were already taken care of by your class