區域性變數

區域性變數(與其他變數類不同)沒有任何字首

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"