I'm following along with 'Why's Poignant Guide to Ruby' in order to learn Ruby and I am having some problem when he first introduces the 'require' method(?) in his tutorial.
Essentially I make a file called 'wordlist.rb' which contains:
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'
}
I then have another ruby scipt called 'files.rb':
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)
Any idea how to get the 'require' to work properly to reference wordlist?
There is a problem with local variable. You can look here - there is exactly the same problem with a solution.
精彩评论