我一直在使用Why's Poignant Guide to Ruby而且我被困在一个特定的例子上。代码要求创建两个文件,其中一个使用require 'wordlist'
链接到另一个(原来不起作用,但在收到错误并搜索后我发现在1>之前添加了./
i> wordlist
作为解决方案)。
重新输入几次,然后只是复制粘贴后,会出现Enter your idea:
提示符,但之后我收到错误消息:
test.rb:6:in '<main>': undefined local variable or method 'code_words' for main:Object (NameError)
我从中得到的是主文件仍然无法识别wordlist.rb
中声明的变量?谢谢,我真的很陌生!
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'
}
test.rb:
require './wordlist'
print "Enter your new idea: "
idea = gets
code_words.each do |real, code|
idea.gsub!( real, code )
end
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
答案 0 :(得分:0)
不能在不同文件之间共享本地变量。无法从code_words
访问wordlist.rb
中定义的test.rb
。您需要将它们放在单个文件中,或者使用具有适当范围的常量或不同类型的变量(实例,类或全局)。
答案 1 :(得分:0)
code_words
是一个局部变量。局部变量是它们定义的范围的本地变量,这就是它们被称为本地变量的原因。 code_words
在wordlist.rb
脚本的范围内定义。它在其他任何地方都没有 。