Class Variables and Methods in Ruby

Class Variables and Methods in Ruby

Classes are like the blueprint from which individual objects are created.

  1. Class variables
  2. Class methods
  3. Private Methods

Class Variables

  1. Class variables are used to store values related to a class in general rather than a particular instance.
  2. Class Variables have a class-scope.
  3. Class variables are typically used to store information regarding the class as a whole.
  4. A class variable looks like this “@@variable_name”.
  5. We can access our class variables anywhere in our class: in both class and instance methods.
  6. A class variable can be used to store a collection of instances of that class.

Class Methods

  1. Class methods are similarly used for implementing behavior that is related to a class in general rather than an instance.
  2. Class methods have a class-scope.
  3. Class methods enact behaviors that belong to the whole class.

A class method is defined like this:

def self.class_method_name
  # some code
End

Class Constants

It's defined using all capital letters, like so:

class User
  ROLES = ["Admin", "Moderator", "Contributor"]
end

The key distinction is that class constants are used to store data that doesn't change (is constant), while class variables are used to store data that does change. Scope-wise, class constants can also be accessed from outside of the class using this syntax:

Album::GENRES

Public, Private & Protected Methods

  1. Public methods are called by an explicit receiver.
  2. Private methods can only be called within the context of the defining class: the receiver of a private method is always “self”.
  3. Private methods are a way of encapsulating functionality within a class.
  4. Private methods also signal to other developers that this method is depended on by other methods in your program.
  5. Private methods are usually written with the word “private“ above them.
  6. Private methods restrict an outsider from calling methods that belong to an object.

Custom Errors

To build a custom error, we define an error class that inherits from the Exception class.

class PartnerError < StandardError
end

The raise keyword tells our program to raise our brand new PartnerError. The rescue allows our program to continue running.

begin
  raise YourCustomError
  rescue YourCustomError
end

“begin/rescue” syntax is used as another form of control flow to handle exceptions.

Object inheritance

  • In Ruby, classes can inherit from one another. This means that they adopt all of the attributes and behaviors (i.e. all of the methods) of the parent, also called the super class.
  • The use of inheritance allows us to create a family of classes with shared behavior, while still differentiating those classes.
  • Inheritance provides an opportunity to reuse the code functionality and fast implementation time.

    Steps for Inheritance

  • Define the super class.
  • Define the subclass
  • Method overriding..(overwriting inherited methods)
# define a class
class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end
   # instance method
   def getArea
       @width * @height
   end
end
# define a subclass
class BigBox < Box

# add a new instance method
   def printArea
      @area = @width * @height
      puts "Big box area is : #@area"
   end
end
# create an object
box = BigBox.new(10, 20)
# print the area
box.printArea()

MODULES

A module is a collection of methods,constants and class variables. Modules are defined as a class but with the module keyword not with class keyword.

Important Points About Module

  1. You cannot inherit modules or you can’t create a subclass of a module
  2. Objects cannot be created from a module
  3. Modules are used as namespaces and as mixins
  4. All the classes are modules, but all the modules are not classes
  5. The class can use namespaces, but they cannot use mixins like modules
  6. The name of a module must start with a capital letter

Syntax:

module Module_name

   # statements to be executed

end

Super

  • What if there is a method in the parent class that we want our child to share some of the functionality of?
  • Or what if we want our child class to inherit a method from the parent and then augment it in some way?
  • We can achieve this with the use of the super keyword.

METAPROGRAMMING

Metaprogramming gives Ruby the ability to open and modify classes, create methods and much more. Metaprogramming allows us to build a class with dynamic attributes.

Benefits:

  1. Use of Keyword arguments makes our Ruby methods more flexible by allowing arguments to be passed in any order.
  2. Helps in writing DRYer, lighter, more intuitive and more scalable codes.
  3. We can dynamically add getters and setters methods
  4. We can make classes more flexible by adding any number of attributes based on our needs at the time without editing.

TOPICS:

Position Argument Keyword Argument Send Method Mass Assignment

### send()

The send method “send” a message to an object instance and it’s ancestors in class hierarchy until the method “reacts”, because the name matches the first argument. It dynamically calls on a method. It is used to assign attributes dynamically. This saves a lot of typing.