Local, Global, Instance, and Class Variables
In this page:
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.
Example: Local, Global, Instance, and Class Variables
$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}"
Login to try C/C++/Java/PHP code in the editor
- Using a local variable inside a method that was defined outside it, which raises
NameErrorbecause methods do not see outer locals. - Using
@@countclass variables and being surprised that subclasses share them. - Reading an uninitialised
@countin an instance, which givesnilinstead of an error.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: