ruby-on-rails - “要求”方法不起作用 - 帮助?

标签 ruby-on-rails ruby

我刚刚开始学习 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/

相关文章:

ruby-on-rails - Google App Engine + Postgres Cloud SQL 连接问题

ruby - 将字符串数组分类为关闭正则表达式

ruby - 当两个图像非常相似时,如何使 Selenium 测试通过?

ruby-on-rails - 用户的未定义方法 'devise'

ruby - 如何使自定义 Ruby 类型的行为像字符串一样?

javascript - 在 Rails 生产中禁用 Assets 缩小

ruby-on-rails - Rspec 和 Capybara 未定义的局部变量或方法 `page'

ruby - 如何在 ruby​​ 中使用 TcpServer.new(0) 开始查找 TcpServer 的端口

mysql - Rails 查询 : Where association is the parent's first associated record?

javascript - facebook 评论(Facebook 社交插件)仅在我刷新 rails 4 应用程序中的页面后加载