我刚开始学习Ruby,我一直在关注为什么(尖锐的)指南。有一次,我创建了一个名为'wordlist.rb'的文件,其中包含以下代码:
code_words = {
'starmonkeys' => 'Phil and Pete, those prickly chancellors of the New Reich',
'catapult' => 'chucky go-go', 'firebomb' => 'Heat-Assisted Living',
'Nigeria' => "Ny and Jerry's Dry Cleaning (with Donuts)",
'Put the kabosh on' => 'Put the cable box on'
}
另一个脚本调用wordlist文件中的'require'方法....
require 'wordlist'
# Get evil idea and swap in code words
print "Enter your new idea: "
idea = gets
code_words.each do |real, code|
idea.gsub!( real, code )
end
# Save the jibberish to a new file
print "File encoded. Please enter a name for this idea: "
idea_name = gets.strip
File::open( "idea-" + idea_name + ".txt", "w" ) do |f|
f << idea
end
现在,无论出于何种原因,当我尝试运行上面的脚本时出现此错误:
test.rb:5:未定义的局部变量或方法`code_words'for main:Object(NameError)
它肯定会找到并加载wordlist.rb文件(该方法返回true),但我似乎无法访问code_words哈希。知道是什么导致了这个吗?
答案 0 :(得分:1)
code_words是wordlist.rb中的局部变量。
你能做什么: