Ruby Tutorial

Variables & Types

Local, Instance, Global, and Class variables in Ruby

Dynamic Typing

In Ruby, you don't need to specify a type for your variables. A variable's type is determined by the value it currently holds.
ruby
name = "Alpha"
age = 25

Variable Scopes

Wait! In Ruby, the first character of a variable name tells you its Scope. This is a unique and powerful feature of the language.
PrefixTypeScope
nonelocalAvailable only in the current block/method
@instanceAvailable to a specific instance of a class
@@classShared across all instances of a class
$globalAvailable everywhere in the program
UPPERconstantShould not be changed after creation

Strings and Symbols

Ruby has two common ways to represent text:
  1. String: "hello" - Mutable. Used for data that changes.
  2. Symbol: :hello - Immutable and unique. Used for keys and identifiers. They are much faster and more memory-efficient than strings for comparisons.

Common Data Types

TypeExamples
Integer1, -42
Float3.14, 0.5
Booleantrue, false
Nilnil (The "Nothing" value)
Array[1, 2, 3]
Hash{ key: "value" }

Summary

TermDescription
Localx = 5
Instance@x = 5 (Owned by an object)
ConstantPI = 3.14
Symbol:name (Immutable text identifier)
Interpolation"#{var}" - Inserting variables into strings
MutableAlmost everything in Ruby can be modified at runtime
Best ForWriting clean, self-documenting code
LogicNames matter: the prefix determines the behavior
SafetyDynamic but strong typing (No 1 + "1" errors)
ModernRuby 3.0+ has a new type-checking tool called Steep
StandardUse snake_case for all variable and method names
IdentityVariables in Ruby are references to objects