2010-09-25 41 views
4

我有一個循環,我在遠程機器上執行一系列命令:紅寶石,我怎麼能訪問外面做局部變量 - 循環結束


    ssh.exec('cd /vmfs/volumes/4c6d95d2-b1923d5d-4dd7-f4ce46baaadc/ghettoVCB; ./ghettoVCB.sh -f vms_to_backup -d dryrun') do|ch, stream, data| 
            if #{stream} =~ /vmupgrade/ 
            puts value_hosts + " is " + data 
            puts #{stream} 
            puts data 
            end 
          end 

我想訪問#{流}和數據外端循環

我將不勝感激任何幫助。 謝謝,

嗨約爾格,

我實現了您的建議,但現在我得到錯誤:


WrapperghettoVCB.rb:49: odd number list for Hash 
     communicator = {ch: ch, stream: stream, data: data} 
         ^
WrapperghettoVCB.rb:49: syntax error, unexpected ':', expecting '}' 
     communicator = {ch: ch, stream: stream, data: data} 
         ^
WrapperghettoVCB.rb:49: syntax error, unexpected ':', expecting '=' 
     communicator = {ch: ch, stream: stream, data: data} 
            ^
WrapperghettoVCB.rb:49: syntax error, unexpected ':', expecting '=' 
     communicator = {ch: ch, stream: stream, data: data} 
               ^
WrapperghettoVCB.rb:76: syntax error, unexpected kELSE, expecting kEND 
WrapperghettoVCB.rb:80: syntax error, unexpected '}', expecting kEND 
+0

對不起,這是用'符號'鍵'Hash's的新的Ruby 1.9'Hash'文字語法。只需用':foo => bar'替換所有'foo:bar'。 I.e .:'communicator = {:ch => ch,:stream => stream,:data => data}'。 – 2010-09-28 19:45:53

回答

19

你不能。局部變量在其範圍內是局部的。這就是爲什麼他們被稱爲局部變量

你可以,但是,使用可變外部範圍:

communicator = nil 

ssh.exec('...') do |ch, stream, data| 
    break unless stream =~ /vmupgrade/ 
    puts "#{value_hosts} is #{data}", stream, data 
    communicator = {ch: ch, stream: stream, data: data} 
end 

puts communicator 

BTW:有在你的代碼了幾個錯誤,這會從工作反正無論您的問題變的防止它因爲您使用了錯誤的語法來取消引用局部變量:取消引用變量的語法只是變量的名稱,例如foo,而不是#{foo}(這只是一個語法錯誤)。

此外,還有一些其他的改進:

  • 格式化:用於Ruby的壓痕的標準爲2位,不26
  • 格式化:用於Ruby的壓痕的標準是2位,而不是0
  • 格式:通常,塊參數與do關鍵字分開,並且空格
  • 後衛條款:如果您纏繞整個體塊或方法的一個條件,只需更換與保護一個一個跳過整個塊的塊的開始。如果條件爲真
  • 字符串插值:在Ruby中添加字符串與+是不尋常的; 如果你需要連接字符串,您通常<<做到這一點,但更多的,往往不是字符串插值首選
  • 多個參數puts:如果您傳遞多個參數puts,將打印所有的人在一個單獨的行上,你不需要多次調用它
5
c, s, d = [nil] * 3 
str = '...' 
ssh.exec str do |ch, stream, data| 
    c, s, d = ch, stream, data 
    if #{stream} =~ /vmupgrade/ 
    puts value_hosts + " is " + data 
    puts #{stream} 
    puts data 
    end 
end 

有人可能會建議您剛纔提到外範圍的變量,如塊參數,但是最近Ruby中塊參數名稱的範圍已經發生了變化,我會建議儘可能安全地使用這種方法。

我不明白在代碼片段中發生了什麼,但常規設計模式通常用於產生OS對象的句柄以及在塊完成後自動關閉/關閉/等等的東西,因此保留Ruby對象包裝可能沒有用處。

+3

順便說一句:我不得不對第一行有所疑問。如果你真的想得到漂亮的,我認爲'c,s,d = []'不那麼鈍,但我更喜歡'c = s = d = nil'。 – 2010-09-25 19:11:10