局部變量由小寫字母或下劃線(_)開頭.局部變量不像全局和實變量一樣在初始化前含nil值.
ruby> $foo
nil
ruby> @foo
nil
ruby> foo
ERR: (eval):1: undefined local variable or method `foo' for main(Object)
對局部變量的第一次賦值做的很像一次聲明.如果你指向一個未初始化的局部變量,Ruby解釋器會認為那是一個方法的名字;正如上面所見錯誤
信息的.
一般的,局部變量的范圍會是
proc{...}
loop{...}
def...end
class...end
module...end
整個程序(除非符合上面某個條件)
下面的例子,define?是一個檢查標識符是否已定義的操作符.如果已定義它將返回標識符的描述,否則返回nil.正如你所見的,bar的范圍是
loop的局部變量;當loop退出時,bar無定義.
ruby> foo = 44; print foo, "/n"; defined? foo
44
"local-variable"
ruby> loop{bar=45; print bar, "/n"; break}; defined? bar
45
nil
一個范圍內的過程對象共享這個范圍內的局部變量.這里,局部變量 bar 由 main 和過程對象 p1, p2共享:
ruby> bar=0
0
ruby> p1 = proc{|n| bar=n}
#<Proc:0x8deb0>
ruby> p2 = proc{bar}
#<Proc:0x8dce8>
ruby> p1.call(5)
5
ruby> bar
5
ruby> p2.call
5
注意開始的"bar=0"不能省略;此賦值允許bar的范圍被 p1和 p2共享.不然 p1, p2 將會分別生成并處理它們自己的局部變量 bar, 調用 p2
也將導致"未定義局部變量或方法"錯誤.
過程對象的強大在于它們能被作為參數傳遞:共享的局部變量即使傳遞出原范圍也仍然有效.
ruby> def box
| contents = 15
| get = proc{contents}
| set = proc{|n| contents = n}
| return get, set
| end
nil
ruby> reader, writer = box
[#<Proc:0x40170fc0>, #<Proc:0x40170fac>]
ruby> reader.call
15
ruby> writer.call(2)
2
ruby> reader.call
2
Ruby對待范圍的辦法相當聰明.顯然,上面例子里 contents 變量是由 reader 和 writer 共享的.我們也可以像上面那樣創造多對使用box的
reader-writer;每一對共享一個 contents 變量,對之間不相干擾.
ruby> reader_1, writer_1 = box
[#<Proc:0x40172820>, #<Proc:0x4017280c>]
ruby> reader_2, writer_2 = box
[#<Proc:0x40172668>, #<Proc:0x40172654>]
ruby> writer_1.call(99)
99
ruby> reader_1.call
99
ruby> reader_2.call
15