从Ruby方法返回变量/数组时出错

时间:2012-10-02 20:14:41

标签: ruby

在我的capistrano任务中,我正在调用superfunction方法。不幸的是,它引发了Unexpected Return错误。我需要从superfunction方法中获取输出,以便在我的任务中进一步解析它。

def superfunction(cmd_type, command, client)
    run "#{command}" do |channel, stream, data|
        hostname = "#{channel[:host]}".tr('"','')
        result = "#{data}".to_s.strip
        return hostname, result
    end

end


task :gather, :roles => :hosts do
...
   servername, redhat_version = superfunction("redhat_version", "cat /etc/redhat-release", client)
end

1 个答案:

答案 0 :(得分:0)

正在生成错误,因为在方法返回后调用了块(可能是capistrano在内部存储它)。作为一种简单的解决方法,您可以使用块来获取所需的变量:

def superfunction(cmd_type, command, client)
  run "#{command}" do |channel, stream, data|
    hostname = "#{channel[:host]}".tr('"','')
    result = "#{data}".to_s.strip
    yield(hostname, result)
  end
end

task :gather, :roles => :hosts do
  superfunction("redhat_version", "cat /etc/redhat-release", client) do |servername, redhat_version|
    # Use servername and redhat_version here
  end
end