Ruby无法使用require
发布时间:2020-12-17 03:25:47 所属栏目:百科 来源:网络整理
导读:这是一个新手问题,因为我试图自己学习 Ruby,所以如果它听起来像一个愚蠢的问题,请道歉! 我正在阅读为什么(尖锐的)ruby指南和我在第4章中的示例.我将code_words Hash键入一个名为wordlist.rb的文件中 我打开另一个文件并输入第一行作为require’wordlist.rb
这是一个新手问题,因为我试图自己学习
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 当我执行此代码时,它失败并显示以下错误消息:
我使用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,'w' ) do |f| f << idea end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |