0
0
Rubyprogramming~5 mins

Class declaration syntax in Ruby

Choose your learning style9 modes available
Introduction

Classes help you organize code by grouping related data and actions together.

When you want to model real-world things like a car or a person in your program.
When you need to create multiple similar objects with shared behavior.
When you want to keep your code clean and easy to understand by grouping related methods.
When you want to reuse code by creating new classes based on existing ones.
Syntax
Ruby
class ClassName
  # code goes here
end

Class names start with a capital letter.

Use end to close the class definition.

Examples
This creates an empty class named Dog.
Ruby
class Dog
end
This class Person has a method greet that prints a message.
Ruby
class Person
  def greet
    puts "Hello!"
  end
end
This class Car has an initialize method to set up new objects with make and model.
Ruby
class Car
  def initialize(make, model)
    @make = make
    @model = model
  end
end
Sample Program

This program defines a class Animal with a method speak. Then it creates an object my_pet and calls speak to print a message.

Ruby
class Animal
  def speak
    puts "I make a sound"
  end
end

my_pet = Animal.new
my_pet.speak
OutputSuccess
Important Notes

Remember to use new to create an object from a class.

Instance variables start with @ and belong to each object.

Summary

Classes group related data and methods.

Class names start with a capital letter and end with end.

Use new to create objects from classes.