【问题标题】:'Require' method won't work - help?“要求”方法不起作用 - 帮助?
【发布时间】:2011-11-07 01:39:02
【问题描述】:

我刚刚开始学习 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 哈希。知道是什么原因造成的吗?

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

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

你可以做什么:

  • 定义一个全局变量($wordlist)
  • 定义一个常量(WORDLIST)
  • 定义另一个容器,例如提供数据的类

【讨论】:

  • 谢谢克努特,我会试试上面的。我是在 wordlist.rb 中还是在需要它的文件中将 code_words 定义为全局/常量?
  • 你必须在 wordlist.rb 中完成。您的应用程序可以稍后使用它。
  • @knut 你确定你的意思是 $wordlist 而不是 $code_words 作为全局变量吗? wordlist 是文件名,code_words 是哈希名称。
  • 名称本身并不重要。但是如果我定义一个在文件外使用的常量,我更喜欢文件名和常量之间的相似性。所以我会将code_words 重命名为WORDLIST。但是,如果您愿意,可以保留名称并使用 $code_words。
猜你喜欢
  • 1970-01-01
  • 2012-04-05
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多