【问题标题】:undefined local variable or method `res' for main:Object (NameError)main:Object (NameError) 的未定义局部变量或方法“res”
【发布时间】:2015-09-09 16:14:33
【问题描述】:

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

#!/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

知道我做错了什么吗?

【问题讨论】:

    标签: ruby


    【解决方案1】:

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

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

    【讨论】:

    • 如果我将其声明为全局怎么办? @res
    • @bsteo: @res 不是一个全局变量,它是一个实例变量。但是在纯脚本的上下文中,它并没有太大的区别
    • 刚刚检查过,res = nil@res 让我的代码工作:)
    猜你喜欢
    • 2016-02-14
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多