[Ruby] How do I define and use classes and objects in Ruby?

In Ruby, a class is a blueprint for creating objects (instances of the class). It defines the attributes (variables) and behaviors (methods) that objects of that class will have.

To define a class in Ruby, you use the class keyword followed by the name of the class, typically written in CamelCase. For example:

1class MyClass
2  # class definition goes here

To define attributes (or instance variables) in a class, you use the attr_accessor, attr_reader, or attr_writer methods. These methods create getter and setter methods for the attributes automatically. For example:

1class Person
2  attr_accessor :name, :age
4  def initialize(name, age)
5    @name = name
6    @age = age
7  end

In the above example, the attr_accessor method is used to create getter and setter methods for the name and age attributes. The initialize method is a special method that gets called when a new object is created from the class. It is used to initialize the attributes of the object.

To create an object (instance) of a class, you use the new method. For example:

1person = Person.new("John Doe", 25)

To access the attributes and call methods on an object, you use the dot (.) operator. For example:

1puts person.name
2person.age = 30

In the above example, person.name accesses the name attribute of the person object, and person.age = 30 sets the age attribute of the person object to 30.

You can also define methods in a class to define the behaviors (actions) of the objects. For example:

1class Person
2  # ... attributes and initialize method ...
4  def introduce
5    puts "Hello, my name is #{@name} and I am #{@age} years old."
6  end

In the above example, the introduce method is defined to print a message introducing the person.

To call a method on an object, you again use the dot (.) operator. For example:


This will call the introduce method on the person object and print the message defined in the method.

These are the basics of defining and using classes and objects in Ruby. There are many more advanced concepts and features in Ruby's object-oriented programming capabilities, but this should give you a good starting point.