What is Object-Oriented Programming?
In OOP, data is modeled using objects that encapsulate both data and behavior. Each object is an instance of a class, which defines its properties and methods. Classes allow you to create multiple objects that have the same properties and behavior, and they provide a blueprint for the objects they create.
Classes in Ruby
A class in Ruby is defined using the class keyword followed by the name of the class. The class body is defined within curly braces. For example:
class Cat
attr_accessor :name, :breed
def initialize(name, breed, age)
@name = name
@breed = breed
@age = age
end
def meow
puts "#{name} meows"
end
end
In the example above, we've defined a Cat class with two instance variables :name and :breed. We've also defined an initialize method that sets the values of the instance variables when a new Cat object is created. The meow method simply outputs a string to the console when it's called.
Objects in Ruby
An object in Ruby is an instance of a class. To create an object, you call the new method on the class and pass in any required arguments to the initialize method. For example:
cat= cat.new("Simba", "British Shorthair", 6)
This creates a new Cat object with a name of "Simba" and a breed of "British Shorthair" with an age of 6
Accessing Properties and Methods of Objects
To access the properties of an object in Ruby, you use the dot notation. For example:
puts cat.name
puts cat.breed
puts cat.age
This will output:
Simba
British Shorthair
6
To call a method on an object, you use the dot notation followed by the method name and any required arguments within parentheses. For example:
cat.meow
This will output "Simba meows"
Inheritance in Ruby
Inheritance is a key concept in OOP that allows you to create new classes that are based on existing classes. The new class inherits all the properties and behavior of the parent class, and can also add new properties and behavior.
To create a subclass in Ruby, you use the < operator followed by the parent class name. For example:
class PersianCat< Cat
def play
puts "#{name} plays with his toys."
end
end
In this example, we've created a PersianCat class that inherits from the Cat class. The PersianCat class has all the properties and methods of the Cat class, as well as its own "play" method.
Top comments (0)