这是一个新手问题,因为我试图自己学习Ruby,所以如果它听起来像一个愚蠢的问题,请道歉!
我正在阅读为什么(尖锐的)ruby指南和我在第4章中的示例.我将code_words Hash键入一个名为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
Run Code Online (Sandbox Code Playgroud)
当我执行此代码时,它失败并显示以下错误消息:
C:/MyCode/MyRubyCode/filecoder.rb:5:未定义的局部变量或方法`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
Run Code Online (Sandbox Code Playgroud)
对于这种情况来说绝对过于复杂的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
Run Code Online (Sandbox Code Playgroud)
小智 1
我认为问题可能是 require 在另一个上下文中执行代码,因此运行时变量在 require 之后不再可用。
您可以尝试将其设为常数:
CodeWords = { :real => 'code' }
Run Code Online (Sandbox Code Playgroud)
这将随处可见。
这是关于变量范围等的一些背景。