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.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading