← Back to Ruby Course | Chapter 2: Variables & Types | Lesson 1 of 7

Local, Global, Instance, and Class Variables

Local, Global, Instance, and Class Variables

Ruby distinguishes variable scope by naming convention: local_var is local to its block/method, $global_var is accessible everywhere, @instance_var belongs to a specific object, and @@class_var is shared across all instances of a class. This prefix-based naming is unique to Ruby compared to most other languages, which use separate declaration keywords instead. Global variables are rarely used in practice since they make code harder to reason about.

Warning: Global variables ($var) are almost always considered bad practice in Ruby -- prefer instance or class variables scoped to an object or class.

Example: Local, Global, Instance, and Class Variables

markup
$global_count = 0

class Counter
  @@total_counters = 0

  def initialize
    @count = 0
    @@total_counters += 1
    $global_count += 1
  end
end

Counter.new
Counter.new

puts "Total counters created: #{Counter.class_variable_get(:@@total_counters)}"
puts "Global count: #{$global_count}"
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.