.jpg)
1. Local scope: Variables declared within a method are only accessible within that method.
def my_method
x = 10
puts x
end
my_method # prints 10
puts x # undefined local variable or method `x' for main:Object
2. Instance scope: Instance variables (denoted by the @ symbol) are accessible within the current instance of a class and any methods defined within that instance.
class MyClass
def initialize
@x = 10
end
def my_method
puts @x
end
end
obj = MyClass.new
obj.my_method # prints 10
puts obj.x # undefined method `x' for # (NoMethodError)
3. Global scope: Variables declared outside of any method or class are accessible throughout the program.
$x = 10
def my_method
puts $x
end
my_method # prints 10
puts $x # prints 10
It's generally recommended to use local scope as much as possible to avoid naming conflicts and to make code easier to reason about. Instance scope is useful when you want to share data between methods within a single object, and global scope should be used sparingly as it can introduce unexpected behavior and make code harder to maintain.

0 Comments