'Require' method won't work - help?
I'm just starting to learn Ruby, and I've been following Why's (poignant) guide. At one point, I create a file titled 'wordlist.rb', within which is the following code:
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'
}
Another script calls the 'require' method on the wordlist file....
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
N开发者_Python百科ow, for whatever reason, I get this error when I try to run the script above:
test.rb:5: undefined local variable or method `code_words' for main:Object (NameError)
It's definitely finding and loading the wordlist.rb file (the method is returning true), but I can't seem to access the code_words Hash. Any idea what could be causing this?
code_words is a local variable inside wordlist.rb.
What you can do:
- define a gloibal variable ( $wordlist)
- define a constant (WORDLIST)
- define another container, e.g. a class which provides the data
精彩评论