Method- local variable
Local variables inside a method is not accessible outside the method.
Eg:
def method
x = 2
end
puts x
This will result in an error .
To access variables outside a method. You need to pass in parameters/arguments into the method.
x = ''
def method(x)
x = 2
end
puts method(x)
However, in this case, x is still ' ' . The puts only print the return value of the method , which is 2.
The method do not mutate the caller.
Local variable - block scope.
Local variable that sits outside a block is ACCESSIBLE to inside the block. While local variable that is initialize inside a block is NOT ACCESSIBLE outside the block.
Eg:
x = "Hello"
loop do
puts x
break
end
This is ok
Eg:
loop do
x = "Hello"
break
end
puts x
This will result in an error.
PS: Please take note that IF statement is not considered a block. Therefore any variables initialized in an IF statement is accessible outside the method.
Local variables inside a method is not accessible outside the method.
Eg:
def method
x = 2
end
puts x
This will result in an error .
To access variables outside a method. You need to pass in parameters/arguments into the method.
x = ''
def method(x)
x = 2
end
puts method(x)
However, in this case, x is still ' ' . The puts only print the return value of the method , which is 2.
The method do not mutate the caller.
Local variable - block scope.
Local variable that sits outside a block is ACCESSIBLE to inside the block. While local variable that is initialize inside a block is NOT ACCESSIBLE outside the block.
Eg:
x = "Hello"
loop do
puts x
break
end
This is ok
Eg:
loop do
x = "Hello"
break
end
puts x
This will result in an error.
PS: Please take note that IF statement is not considered a block. Therefore any variables initialized in an IF statement is accessible outside the method.
Comments
Post a Comment