我在file2.rb
下保存了以下哈希codewords = {'starmonkeys' => 'Five edged primates.'}
*有些人可能会从Poignant Guide中认出这一点!
以下是file1.rb:
if __FILE__ == $0
require File.expand_path('C:\Users\COMPAQ\My Documents\Aptana Studio Workspace\why the lucky stiff made me do this\file2.rb', __FILE__)
print "Enter your secret sentence."
idea = gets
codewords.each do | real , code|
idea.gsub!( real , code )
end
#Saving to a new file
print "File encoded. Print a file name for this idea"
idea_name = gets.strip
File::open( "idea-"+idea_name+".txt","w" ) do |f|
f<<idea
end
end
我提出了一个NameError:file.rb:7:in <main>': undefined local variable or method
codewords'for main:Object(NameError)
我做错了什么才能实现这个目标?
答案 0 :(得分:2)
据我所知,变量声明的范围限定在它们所定义的文件中。这意味着它们基本上不存在于文件范围之外。要弥合这一差距,您可能需要使用常量,类或模块,或者这些组合用于命名空间。例如:
# file2.rb
module Codewords
CODEWORDS = { ... }
end
稍后您可以像这样要求和使用:
include Codewords
CODEWORDS.each do |real, code|
# ...
end
答案 1 :(得分:0)
您可以将代码字声明为全局代码,然后通过将其称为
来访问它 $codewords = {'starmonkeys' => 'Five edged primates.'} #file2.rb
然后在file1.rb中:
codewords.each do | real , code|
idea.gsub!( real , code )
end