Local, Global, Instance, and Class Variables
In this page:
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
$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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: