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

Local, Global, Instance, and Class Variables

Ruby has different kinds of variables that can be seen in different places: some just in one spot, some inside one object, some in the whole class, and some everywhere. It is like having a desk drawer, a bedroom shelf, a family cupboard, and a town notice board.
Syntax
ruby
local_var = value
$global_var = value
@instance_var = value
@@class_var = value

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}"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using a local variable inside a method that was defined outside it, which raises NameError because methods do not see outer locals.
  2. Using @@count class variables and being surprised that subclasses share them.
  3. Reading an uninitialised @count in an instance, which gives nil instead of an error.
🔒

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.