Ruby中简单的'require'问题

时间:2009-12-21 23:57:08

标签: ruby require

我正在跟随'为什么是Ruby的尖锐指南'来学习Ruby,当他第一次在他的教程中介绍'require'方法(?)时遇到了一些问题。

基本上我创建了一个名为'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'
}

然后我有另一个名为'files.rb'的ruby scipt:


require 'wordlist'

#Get evil idea and swap in code words
print "Enter your new idea: "
idea = gets

#real will have the key and code will have the value
#Method followed by ! (like gsub!) are known as destructive methods
code_words.each do |real, code|
    safe_idea = idea.gsub!( real,code )
end

#Save the jibberish to a new file
print "File encoded. Please enter a name for this idea: "
idea_name  = gets.strip

File::open( "idea-" + idea_name + ".txt", "w") do |f|
    f 

When I try to run the Ruby script i get:

files.rb:9: undefined local variable or method `code_words' for main:Object (NameError)

知道如何让'require'正常工作以引用wordlist吗?

1 个答案:

答案 0 :(得分:3)

局部变量存在问题。您可以查看here - 解决方案存在完全相同的问题。