ruby
  1. ruby-object-class

Ruby Object Class

The Object class is the ancestor of all classes in Ruby. It is the default root of Ruby's class hierarchy.

Syntax

class ClassName < ParentClass
  # Class body
end

Example

class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def greet
    puts "Hello, my name is #{@name} and I am #{@age} years old."
  end
end

person1 = Person.new("John", 25)
person1.greet

Output

Hello, my name is John and I am 25 years old.

Explanation

The Person class is created using the class keyword, followed by the name of the class and the initialize method which is used to create a new instance of the class with the given arguments. The instance variables @name and @age are assigned values from the arguments passed in.

The greet method is defined to print out a greeting message using the instance variables.

An instance of the Person class is created using the new method and the greet method is called on that instance.

Use

The Object class is used as a parent class for all other classes in Ruby, providing default methods and attributes that can be overridden by subclasses. It is used extensively in object-oriented programming in Ruby to create custom data types with their own behaviors and attributes.

Important Points

  • The Object class is the default root of Ruby's class hierarchy.
  • All classes in Ruby are descendants of Object.
  • The initialize method is used to create a new instance of a class with the given arguments.
  • Instance variables are used to store and manipulate data within an instance of a class.
  • Methods defined in a class are used to define the behavior of instances of that class.

Summary

In summary, the Object class is the foundation of Ruby's object-oriented programming paradigm. It provides default behavior and attributes for all other classes in Ruby, making it a crucial part of the language. By understanding the Object class and how to use it, you can create powerful and flexible applications in Ruby.

Published on: