Ruby,如何访问do-end循环之外的局部变量

Ruby,如何访问do-end循环之外的局部变量,ruby,Ruby,我有一个循环,在远程机器上执行一系列命令: 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/

我有一个循环,在远程机器上执行一系列命令:


   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
我想访问#{stream}和do end循环之外的数据

我将感谢任何帮助。 谢谢

嗨,Jörg

我实施了你的建议,但现在我发现了一个错误:


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
有人可能会建议您只引用外部作用域变量作为块参数,但是Ruby中块参数名称的范围最近发生了变化,我建议您谨慎行事,这样做就可以了


我不明白代码段中发生了什么,但一般设计模式通常用于生成操作系统对象的句柄,以及在块完成后自动关闭/关闭的对象等,因此保留Ruby对象包装器可能没有用处。

你不能。局部变量是其作用域的局部变量。这就是为什么它们被称为局部变量

但是,您可以使用外部范围中的变量:

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
顺便说一句:你的代码中有几个bug,不管你在变量作用域方面有什么问题,都会阻止它工作,因为你使用了错误的语法来取消引用局部变量:取消引用变量的语法只是变量的名称,例如
foo
,而不是
{foo}
(这只是一个语法错误)

此外,还有一些其他改进:

  • 格式:Ruby中缩进的标准是2个空格,而不是26个空格
  • 格式:Ruby中缩进的标准是2个空格,而不是0
  • 格式化:通常,块参数与
    do
    关键字之间用空格分隔
  • guard子句:如果将一个块或方法的整个主体包装在一个条件中,则可以将其替换为块开头的一个保护,如果条件为true,该保护将跳过整个块

  • 字符串插值:在Ruby中,将字符串与
    +
    一起添加是不寻常的;如果需要连接字符串,通常使用
    来连接。顺便说一句:我对第一行有点困惑。如果你真的想变得漂亮,我想
    c,s,d=[]
    没有那么迟钝,但我更喜欢
    c=s=d=nil
    。对不起,这是新的Ruby 1.9
    Hash
    文本语法,用于
    Hash
    es和
    Symbol
    键。只需将所有
    foo:bar
    替换为
    :foo=>bar
    。即:
    communicator={:ch=>ch,:stream=>stream,:data=>data
    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