HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RubyVariablesData TypesOperatorsStringsArraysHash (Dictionary)Conditions (if / else)LoopsMethods (def)Classes
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🗂️ Hash (Dictionary)
🔁 Condition & Loop
🧩 Method & Class
Ruby›Classes

Classes

class, initialize constructor, @instance variables, and methods.

Simple enough for a 5-year-old to understand

class and initialize

Example code
1
class Cat
Define class.
DefinitionDefine class.
2
def initialize(name)
Constructor (runs when the object is born).
FunctionConstructor (runs when the object is born).
3
@name = name
@name property of the object.
Variable@name property of the object.
4
end
5
def meow
Method.
FunctionMethod.
6
"#{@name}: meow"
Use name.
FunctionUse name.
7
end
8
end
End of class.
DefinitionEnd of class.
9
puts Cat.new("Tabby").meow
Tekir: meow
Output / InputTekir: meow
DefinitionFunctionVariableOutput / Input
💡 Hint: Creating an object: Class.new(...). Variables starting with @ belong to the object.

About this topic

In Ruby, a class defines the behavior and state of objects. Since everything is an object, the concept of a class is central to the language: integers, strings, and arrays are all instances of a class, and you write your own classes in the exact same way.

An object's state is stored in variables starting with an at sign, and they CANNOT be accessed from the outside. Reader or writer methods are defined for fields you want to expose; Ruby provides shortcuts to generate these in a single line.

Ruby's class system is unusually open: you can add methods to existing classes later on, even standard library classes. This is a powerful tool, but if used carelessly, it breaks other code; therefore, it is avoided in libraries.

What you will learn

  • Defining classes and creating objects
  • when the initialize method is called
  • Object variables and accessor shortcuts
  • Inheritance and method overriding
  • why the to_s method is defined

Who is this for?

  • Those who want to learn object-oriented design in Ruby
  • Those preparing to learn Rails
  • Those who want to organize their code by dividing it into classes

When to use?

Classes are used when there is data that carries meaning together and operations that work on that data. For simple structures that only carry data, a Struct or hash is sufficient.

Define the to_s method if you want meaningful output when printing the object; otherwise, the class name and object ID are printed.

Common mistakes

Wrong

class Person
  def initialize(name)
    name = name
  end

  def show
    puts @name
  end
end

p1 = Person.new("Ali")
p1.show

Since the assignment was made without the at sign, a local variable was assigned to itself; the object variable was never created and show prints nil. There is no error message, only a blank line appears. Object state is stored in variables starting with an at sign.

Correct

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

  def show
    puts @name
  end
end

p1 = Person.new("Ali")
p1.show

Wrong

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

p1 = Person.new("Ali")
puts p1.name

Object variables cannot be accessed from the outside; the interpreter throws an "undefined method 'name'" error. A reader method is needed to expose it externally, and Ruby provides a shortcut to generate this in a single line. This restriction is intentional: state is only exposed as much as the class allows.

Correct

class Person
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

p1 = Person.new("Ali")
puts p1.name

Wrong

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

p1 = Person.new("Ali")
puts p1

Since to_s is not defined, Ruby prints the default representation: the class name and object ID. It is not an error, but it is unhelpful in debugging. If you want meaningful output, you need to define the to_s method; inspect is used when printing with the p method.

Correct

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

  def to_s
    "Person: #{@name}"
  end
end

p1 = Person.new("Ali")
puts p1

Frequently asked questions

What is the difference between attr_reader, attr_writer, and attr_accessor?

attr_reader generates only a reading method, attr_writer only writing, and attr_accessor both. As a habit, start with attr_reader; open writing permissions only if genuinely required. Making every field writable makes controlling state impossible.

Why is initialize a special method?

When new is called, Ruby creates the object and immediately calls the initialize method. Thus, it is the place to set up the initial state the moment the object is born. You do not call it yourself; new calls it for you.

Is it safe to add methods to an existing class?

Technically possible, but it must be used with caution. A method you add to a standard library class might clash with another library's method of the same name, producing very hard-to-find bugs. Using it sparingly in your own application and never in libraries is the right approach.

Summary

Object state is stored in variables starting with an at sign.

The initialize method runs automatically when new is called.

Object variables cannot be accessed from the outside; they are exposed via accessor methods.

If to_s is not defined, printing outputs the class name and object ID.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code