2011-08-30 109 views
4

我剛剛開始學習Ruby,我一直在關注爲什麼(尖銳)指南。在一個點上,我創建了名爲「wordlist.rb」文件,其內是下面的代碼:'Require'方法不起作用 - 幫助?

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' 
} 

另一個腳本調用的詞表文件中的「需要」的方法....

require 'wordlist' 

# Get evil idea and swap in code words 
    print "Enter your new idea: " 
    idea = gets 
    code_words.each do |real, code| 
    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 << idea 
    end 

現在,不管是什麼原因,我得到這個錯誤,當我嘗試運行上面的腳本:

test.rb:5:未定義的局部變量或方法`code_words'主:對象(NameError)

一世t的確找到並加載wordlist.rb文件(該方法返回true),但我似乎無法訪問code_words散列。任何想法可能會造成這種情況?

+1

http://stackoverflow.com/questions/1943406/simple-require-problem-in-ruby –

回答

1

code_words是wordlist.rb中的局部變量。

你可以做什麼:

  • 定義gloibal變量($單詞表)
  • 定義常量(單詞表)
  • 定義另一個容器,例如一個類提供的數據
+0

謝謝克努特,我會嘗試以上。我在wordlist.rb中將code_words定義爲全局/常量,還是在需要它的文件中定義? – opticon

+0

你必須在wordlist.rb內完成。您的應用程序可以稍後使用它。 – knut

+0

@knut你確定你的意思是$ wordlist而不是$ code_words作爲全局變量嗎? wordlist是文件名,code_words是散列名稱。 – Padawan