Codectionary / Developer documentation / Ruby

Ruby Classes & Modules

Classes define objects and their behaviour. initialize is the conventional constructor method. Modules can group methods and constants, and can be mixed into classes with include.

Syntax

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

Examples

Creating an object

A small, runnable example of this syntax.

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

  def greet
    "Hello, #{@name}!"
  end
end

puts Greeter.new("Ada").greet

Best practices

  • Keep instance state private behind clear methods; expose only the operations callers genuinely need.
  • Keep examples small while learning, then combine the idea with a real project.

At a glance

Purpose
Expressive scripting and applications
File extension
.rb
Runs in
Ruby interpreter
Usually used with
Ruby standard library and gems

Specifications & further reading

Related Ruby documentation