我正试图在大海捞针中找到针头。我已经收到了带有两个值和键的字典。
ruby haystack.rb
{"haystack"=>["D0zVh", "F1PFc", "j1WMn", "Ebz3k", "SE7gZ", "kOa7j", "0vCJb", "px18q", "NJSyl", "nRsOK", "T7t8F", "2jvwZ", "5414s", "q5z8U", "TI2Zm", "v4Bn9", "5dRcM", "M84vp", "8nQ0o", "OxEKw"], "needle"=>"v4Bn9"}
第一个值needle是字符串。第二个值haystack是一个字符串数组。 下一步是告诉API针在大海捞针阵列中的位置。
我需要将结果发布到" api / validateneedle",使用我的令牌的密钥令牌,以及表示针位于haystack数组中的整数的关键针。
当我运行此文件时,出现以下错误:
haystack.rb:59:in `<main>': undefined local variable or method `token' for main:Object (NameError)
任何人都可以告诉我为什么我收到此错误消息?我非常感谢任何帮助/反馈!
token_info = {:token => "SVilLuY0OU"}
require 'net/http'
http = Net::HTTP.new("challenge.code2040.org")
# Sending json in body of http request
# Creating a request that will use the post http method
require "json"
body = token_info.to_json
request = Net::HTTP::Post.new("/api/haystack")
# Setting the request body to be our json
request.body = body
# Storing my token in a variable
response = http.request(request)
# Printing my token to complete rest of assignment
#Printing the body of the response
response_hash = JSON.parse(response.body)
puts response_hash["result"]
def getIndex(response)
needle = response["result"]["needle"]
haystack = response["result"]["haystack"]
i = 0
while i < haystack.length
# if we find it, break the loop and return i
if haystack[i] == needle
return i.to_s
end
i += 1
end
return "not found"
end
def sendIndex(token)
response = getItems(token)
index = getIndex(response)
params = {'token' => token, 'needle' => index}
request = Net::HTTP::Post.new("/api/validateneedle")
end
sendIndex(token)
答案 0 :(得分:0)
错误消息不言自明:在第59行,您将参数token
传递给方法sendIndex
,但token
未定义,既不是方法也不是作为一个局部变量。