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
defDefault parameterclass / initialize
Ruby›REFERENCE›Method & Class
🧩

Method & Class

Defining methods (functions) and classes.

CommandDescription
defDefines a method (function).
Default parameterDefault value for a parameter.
class / initializeDefines your own type (class).

def

Try it yourself →

Defines a method (function).

Syntax

def name(param)
  ...
end

Description

Defined with def. Ruby automatically returns the value of the last expression (no need to write return, though you can).

Example

def square(x)
  x * x
end
puts square(5)

Expected output

25

When to use?

Preventing code repetition.

Common mistakes

  • ⚠️ Don't forget end. return is optional; the last line is returned anyway.

Default parameter

Try it yourself →

Default value for a parameter.

Syntax

def name(x, y = default)

Description

If no argument is provided, the default is used.

Example

def greet(name, message = "Hello")
  "#{message} #{name}"
end
puts greet("Alex")

Expected output

Hello Alex

When to use?

Optional arguments.

class / initialize

Try it yourself →

Defines your own type (class).

Syntax

class Name
  def initialize(p)
    @field = p
  end
end

Description

Classes are defined with class. initialize is the constructor method (runs when an object is created). @area is an instance variable (belongs to the object).

Example

class Cat
  def initialize(name)
    @name = name
  end
  def meow
    "#{@name}: meow"
  end
end
puts Cat.new("Tabby").meow

Expected output

Tabby: meow

When to use?

Object-oriented design.

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