Local Variables
suggest changeLocal variables (unlike the other variable classes) have no prefix.
local_variable = "local"
p local_variable
# => "local"
Their scope depends on where they were assigned. They cannot be used outside that scope. For example, a local variable assigned in a method can only be used inside that method.
def some_method
method_scope_var = "hi there"
p method_scope_var
end
some_method
# "hi there"
# => "hi there"
method_scope_var
# NameError: undefined local variable or method 'method_scope_var' for main
Local variables are not limited to methods. A name first assigned inside a do ... end block, or a block written with curly braces {}, stays in that block. Assigning a name that already exists outside the block updates the outer variable. Block parameters are local to the block.
2.times do |n|
local_var = n + 1
p local_var
end
# 1
# 2
# => 2
local_var
# NameError: undefined local variable or method 'local_var' for main
However, local variables declared in if or case blocks can be used in the parent-scope:
if true
usable = "yay"
end
p usable
# "yay"
# => "yay"
A local variable cannot be used outside the block where it was created, but an outer local can be read inside a block:
my_variable = "foo"
my_variable.split("").each_with_index do |char, i|
puts "The character in string '#{my_variable}' at index #{i} is #{char}"
end
# The character in string 'foo' at index 0 is f
# The character in string 'foo' at index 1 is o
# The character in string 'foo' at index 2 is o
# => ["f", "o", "o"]
But not to method / class / module definitions
my_variable = "foo"
def some_method
puts "you can't use the local variable in here, see? #{my_variable}"
end
some_method
# NameError: undefined local variable or method 'my_variable' for main
The variables used for block arguments are (of course) local to the block, but will overshadow previously defined variables, without overwriting them.
overshadowed = "sunlight"
["darkness"].each do |overshadowed|
p overshadowed
end
# "darkness"
# => ["darkness"]
p overshadowed
# "sunlight"
# => "sunlight"