Ruby 无法使用 require

标签 ruby path require

这是一个新手问题,因为我正在尝试自己学习 Ruby,如果这听起来像一个愚蠢的问题,我们深表歉意!

我正在阅读第 4 章中为什么(尖锐的)ruby 指南的示例。我将 code_words 哈希输入到一个名为 wordlist.rb 的文件中

我打开了另一个文件并输入了第一行作为 require 'wordlist.rb' 和下面的代码的其余部分

#Get evil idea and swap in code
print "Enter your ideas "
idea = gets
code_words.each do |real, code|
    idea.gsub!(real, code)
end

#Save the gibberish to a new file
print "File encoded, please enter a name to save the file"
ideas_name = gets.strip
File::open( 'idea-' + ideas_name + '.txt', 'w' ) do |f|
    f << idea
end

当我执行此代码时,它失败并显示以下错误消息:

C:/MyCode/MyRubyCode/filecoder.rb:5: undefined local variable or method `code_words' for main:Object (NameError)

我使用的是 Windows XP 和 Ruby 版本 ruby​​ 1.8.6

我知道我应该设置类似 ClassPath 的东西,但不确定在哪里/如何设置!

非常感谢!

最佳答案

虽然所有文件的顶层都在相同的上下文中执行,但每个文件都有自己的局部变量脚本上下文。换句话说,每个文件都有自己的一组局部变量,可以在整个文件中访问,但不能在其他文件中访问。

另一方面,常量 (CodeWords)、全局变量 ($code_words) 和方法 (def code_words) 可以跨文件访问。

一些解决方案:

CodeWords = {:real => "code"}

$code_words = {:real => "code"}

def code_words
  {:real => "code"}
end

对于这种情况来说绝对过于复杂的 OO 解决方案:

# first file
class CodeWords
  DEFAULT = {:real => "code"}

  attr_reader :words
  def initialize(words = nil)
    @words = words || DEFAULT
  end
end

# second file
print "Enter your ideas "
idea = gets
code_words = CodeWords.new
code_words.words.each do |real, code|
  idea.gsub!(real, code)
end

#Save the gibberish to a new file
print "File encoded, please enter a name to save the file"
ideas_name = gets.strip
File::open( 'idea-' + ideas_name + '.txt', 'w' ) do |f|
  f << idea
end

关于Ruby 无法使用 require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1061121/

相关文章:

ruby-on-rails - 将输出重定向到 stderr

html - Rails - 在 application.html.erb 中修改 html 类的正确方法是什么?

python - 分发独立的 libpython 路径

ruby - (...)在 `require' : no such file to load -- 'gemname' (LoadError)

ruby - 去掉ruby项目中的很多require_relatives

ruby-on-rails - Bundle exec rake 不在 cron 中运行

ruby-on-rails - 我们可以编写没有哈希类的哈希吗?

Java 文件输出流 : path relative to program folder?

Java获取资源相对路径

require - Angular 6::找不到名称 'require'