Almost everything in ruby is an object. Class names in ruby use CamelCase. initialize
is a method used to boot up each object the class creates. Use @
before a variable to signify that it always is an instance variable. This means that the variable is attached to the instance of the class.
@
- whenever a class is created, it has to have your @
and each instance of your class will have its own @
. Scope of a variable is the context in which it is visible to the program.
Global variable - available everywhere
Local variable - only available in methods
Class - only available in classes
Instance - only available in instances of classes.
Class variable begin with @@
Global variables inside a method or class begin with $
Inheritance - process by which one class takes on the attributes and methods of another. It is used to express and is-a relationship. When you call super
from inside a method, that tells ruby to look in the superclass of the current class and find a method with the same name as the one from which super
is called. If it finds it, ruby will us the superclass version of the method. Mixins, allow for data and functions of multiple classes to be put in one.
If you want to end a ruby statement without going on a new line you can just type a semicolon.
Public methods allow for an interface with the rest of the program. Private methods are for classes to do their work undisturbed. In private methods, methods cannon be called with an explicit receiver. in order to access private info we have to create public methods such as attr_reader
and attr_writer
. These are shorthand notations for defining getter and setter methods within a class for instance variables. Important in object orienting encapsulation principle.
module - a toolbox that contains a set of methods and constants. These are written in CamelCase. Constants included in methods are defined with all caps.
name-spacing - how ruby separated methods and constants.
scope resolution operation - ruby's way of saying it tells rubys where you're looking for a specific bit of code.
If we say Math::PI
ruby knows to look inside the math module to get that PI, not any other PI.
In the following code : def initialize (name, balance=100)
This signifies an optional parameter
Ruby is saying that you can pass 1 or 2 arguments to initialize
. If you pass 2, it uses your balance argument to set @balance
. If you only pass name
, balance
gets a default value of 100 and this is what is stored in balance
.
In Ruby , private methods can be called without an explicit receiver within the context of a class.
Top comments (0)