GGistDev

Variables in Ruby

Names bind to objects; scope is lexical and typing is dynamic.

Kinds of variables

Local, instance, class, and global variables control visibility and lifetime. Class variables are shared across a class hierarchy—use sparingly.

x = 1            # local
@count = 0       # instance
@@total = 0      # class (shared across hierarchy; use sparingly)
$stdout.sync = true  # global (avoid in libraries)

Declaration and initialization

Ruby creates locals on first assignment. Reading an unassigned local raises a NameError.

# y  # NameError if referenced before assignment
y = 10

Multiple assignment, splats, and swap

Parallel assignment, splats for remainder, and easy swapping are idiomatic.

a, b = 1, 2
a, b = b, a
first, *rest = [1, 2, 3, 4]   # rest => [2,3,4]
_, second = 10, 20            # ignore with underscore by convention

Scope basics and blocks

Methods create their own scope; block parameters are local to the block. Instance variables are available across instance methods.

def greet(name)
  message = "Hi, #{name}"
  message
end

[1,2,3].each do |n|
  # block parameter n is local to the block
end

Class vs class instance variables

Prefer class instance variables (@var on the class object) over @@var (shared across hierarchy).

class Counter
  @count = 0
  class << self; attr_accessor :count end
end

Globals and environment

Global variables are process‑wide. Prefer ENV for environment configuration.

ENV["PORT"]      # => "3000" (string)
$VERBOSE = true  # enable warnings globally (be careful)

Summary

  • Prefer locals and instance vars; avoid globals and most class vars
  • Use parallel assignment and splats for concise, readable code