我刚刚开始学习 Ruby,我一直在关注 Why 的(尖锐的)指南。有一次,我创建了一个名为“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: main:Object (NameError) 的未定义局部变量或方法“code_words”
肯定是在查找并加载 wordlist.rb 文件(该方法返回 true),但我似乎无法访问 code_words 哈希。知道是什么原因造成的吗?
最佳答案
code_words 是 wordlist.rb 中的局部变量。
你可以做什么:
- 定义一个全局变量($wordlist)
- 定义一个常量(WORDLIST)
- 定义另一个容器,例如一个提供数据的类
关于ruby-on-rails - “要求”方法不起作用 - 帮助?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7248144/