DEV Community

Kat
Kat

Posted on

Classes

Classes serve as a blueprint for instances of objects in programming. Today I learned about creating classes in Ruby. A few notes:

-We only use capital letters in Ruby when referring to classes.
-A multi-word class name should be in CamelCase.
-The keyword attr_accessor is used to declare the attributes of a class.
-We can define our own methods within a class using the keyword def.

Here is an example of a class with a class method.

class Cat
  attr_accessor :name
  attr_accessor :age
  attr_accessor :fur_color

  def meow
    return self.name + " says 'Meow!' :3"
  end
end
Enter fullscreen mode Exit fullscreen mode

Another important keyword in classes is self. According to the learn materials, this keyword "refers to the class it is inside of and can be used to refer to all the attributes of that class".

Additionally, this module discusses inheritance, which is one of the four pillars of object-oriented programming, or OOP, the most commonly used modern programming paradigm. Inheritance basically means that you can create subclasses of any class that inherit the attributes and methods of the parent class (but also have their own!).

The syntax to a subclass is:

class SubClass < ParentClass

Top comments (0)