Ruby Object Orientation

Object-oriented programming is a programming paradigm that is based on the concept of "objects", which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).

Ruby is a pure object-oriented language, meaning everything in Ruby is an object, even data types like integers, booleans, and "nil".

Here are the basic concepts of OOP in Ruby:

  • Class: A blueprint for creating objects. A class defines what attributes an instance of this class will have, like "name", "age", etc, and what methods it will have.
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end
end
  • Object: An instance of a class. An object is created from a class. In Ruby, objects are created by calling the .new method on a class.
person = Person.new("John", 30)
  • Attribute: A property of an object. Attributes are defined in the class and each object of that class has those attributes.
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def name
    @name
  end

  def age
    @age
  end
end
  • Method: A procedure or function associated with a class. Methods define the behavior of objects.
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def introduce
    "Hello, my name is #{@name} and I am #{@age} years old."
  end
end
  • Inheritance: A class can inherit attributes and methods from another class.
class Employee < Person
  def initialize(name, age, job_title)
    super(name, age)
    @job_title = job_title
  end

  def introduce
    "Hello, my name is #{@name}, I am #{@age} years old, and I am a #{@job_title}."
  end
end
  • Encapsulation: The practice of keeping fields within a class private. This means that the fields can only be manipulated through methods of the class.
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def increase_age
    @age += 1
  end

  def age
    @age
  end
end
  • Polymorphism: The ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
class Animal
  def make_sound
    "..."
  end
end

class Cat < Animal
  def make_sound
    "Meow"
  end
end

class Dog < Animal
  def make_sound
    "Woof"
  end
end

That's a very basic introduction to OOP in Ruby. Each of these topics could be expanded on significantly, but this should give you a good starting point.