2011-08-30 108 views
4

我刚刚开始学习Ruby,我一直在关注为什么(尖锐)指南。在一个点上,我创建了名为“wordlist.rb”文件,其内是下面的代码:'Require'方法不起作用 - 帮助?

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' 
} 

另一个脚本调用的词表文件中的“需要”的方法....

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'主:对象(NameError)

一世t的确找到并加载wordlist.rb文件(该方法返回true),但我似乎无法访问code_words散列。任何想法可能会造成这种情况?

+1

http://stackoverflow.com/questions/1943406/simple-require-problem-in-ruby –

回答

1

code_words是wordlist.rb中的局部变量。

你可以做什么:

  • 定义gloibal变量($单词表)
  • 定义常量(单词表)
  • 定义另一个容器,例如一个类提供的数据
+0

谢谢克努特,我会尝试以上。我在wordlist.rb中将code_words定义为全局/常量,还是在需要它的文件中定义? – opticon

+0

你必须在wordlist.rb内完成。您的应用程序可以稍后使用它。 – knut

+0

@knut你确定你的意思是$ wordlist而不是$ code_words作为全局变量吗? wordlist是文件名,code_words是散列名称。 – Padawan