Morton Goldberg
8/9/2007 3:06:00 AM
On Aug 8, 2007, at 7:57 PM, Howard Fine wrote:
> I just started tinkering with Ruby. From "The Poignant Ruby
> Programmer"
> or whatever it's called (you know what I mean) I tried running the
> small
> example but get an error.
> This is the first file called m2.rb:
>
> require '/usr/home/me.rb'
>
> # 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
>
> And this is me.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'
> }
>
> When I do: ruby me2.rb and enter any of the code_words above, I get:
>
> me2.rb:6: undefined local variable or method `code_words' for
> main:Object (NameError)
require is working fine. What you have is a scoping problem. The
following shows a couple of ways to fix it.
<code -- me.rb>
$code_words = {
'starmonkeys' => 'Phil and Pete, those prickly chancellors of the
NewReich',
'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'
}
CODE_WORDS = {
'starmonkeys' => 'Phil and Pete, those prickly chancellors of the
NewReich',
'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'
}
</code?>
<code -- me.rb>
require "/Users/mg/Desktop/me" # I put it in a different place, but
makes no difference
# global variable
$code_words # => {"Nigeria"=>"Ny and Jerry's Dry Cleaning (with
Donuts)", "firebomb"=>"Heat-Assisted Living", "catapult"=>"chucky go-
go", "Put the kabosh on"=>"Put the cable box on",
"starmonkeys"=>"Phil and Pete, those prickly chancellors of the
NewReich"}
# constant -- note leading ::
::CODE_WORDS # => {"Nigeria"=>"Ny and Jerry's Dry Cleaning (with
Donuts)", "firebomb"=>"Heat-Assisted Living", "catapult"=>"chucky go-
go", "Put the kabosh on"=>"Put the cable box on",
"starmonkeys"=>"Phil and Pete, those prickly chancellors of the
NewReich"}
</code?>
Regards, Morton