局部变量

局部变量(与其他变量类不同)没有任何前缀

local_variable = "local"
p local_variable
# => local

它的范围取决于它的声明位置,它不能在声明容器​​范围之外使用。例如,如果在方法中声明了局部变量,则只能在该方法中使用它。

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'

当然,局部变量不仅限于方法,根据经验你可以说,只要你在 do ... end 块中声明一个变量或用花括号 {} 包裹它就会是本地的并且作用于它的块。声明。

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'

但是,在 ifcase 块中声明的局部变量可以在父作用域中使用:

if true
    usable = "yay"
end

p usable
# yay
# => "yay"

虽然局部变量不能在其声明块之外使用,但它将传递给块:

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"]

但不是方法/类/模块定义

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'

用于块参数的变量(当然)是块的本地变量,但会覆盖以前定义的变量,而不会覆盖它们。

overshadowed = "sunlight"

["darkness"].each do |overshadowed|
    p overshadowed
end
# darkness
# => ["darkness"]

p overshadowed
# "sunlight"
# => "sunlight"