undefined局部变量或方法`res'for main:Object(NameError)

时间:2015-09-09 08:02:51

标签: ruby

我有以下连接到主机的小脚本,并获得一些输出。

#!/usr/bin/env ruby

require 'net/http'
require 'net/https'
require 'timeout'

serverurl = "http://www.google.com/"

uri = URI(serverurl)

res = Net::HTTP.post_form(uri, 'method' => 'login', 'username' => 'admin', 'password' => 'MySup3rDup3rp@55w0rd')

cookie = res['set-cookie']
if cookie.nil?
  puts "No cookie"
end

我想使用一些超时,所以我这样做:

#!/usr/bin/env ruby

require 'net/http'
require 'net/https'
require 'timeout'

serverurl = "http://www.google.com/"

uri = URI(serverurl)

begin
  timeout(10) do
    res = Net::HTTP.post_form(uri, 'method' => 'login', 'username' => 'admin', 'password' => 'MySup3rDup3rp@55w0rd')
  end
rescue StandardError,Timeout::Error
  puts "#{server} Timeout"
  exit(1)
end

cookie = res['set-cookie']
if cookie.nil?
  puts "No cookie"
end

现在我收到一些错误:

test.rb:20:in `<main>': undefined local variable or method `res' for main:Object (NameError)

我不知道为什么,因为类似的测试代码可以正常工作:

require "timeout"

begin
  timeout(6) do
    sleep
  end
#rescue # under ruby >= 1.9 is ok
rescue StandardError,Timeout::Error # workaround for ruby < 1.9
  p "I'm sorry, Sir. We couldn't make it, Sir."
end

知道我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

这是关于范围。在Ruby中,变量只在定义它们的同一范围内可见(例外是实例,类和全局变量以及常量)。

因此,在您的示例中,res仅在timeout - 块中可见。在res = nil - 块之前添加begin,以确保在您实际需要该值的范围内定义res