Why's (poignant) Guide to Ruby - code question


I try to follow an example in why’s (poignant) Guide to Ruby. File
‘wordlist.rb’ is created with the following content:

code_words = {
‘starmonkeys’ => ‘Phil and Pete, those prickly chancellors of the New
‘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’

In another file this line:

require ‘wordlist’

and subsequent use of variable code_words.

But code_words gets flagged by the interpreter as an ‘undefined local
variable’ and I cannot run the code.

How can I get variable code_words in the desired scope?

Post an example program that is no longer than 5 lines that demonstrates
the problem. Also state what what directory each file is in.

I found out that local variables in the required file are lost to the
calling file. This fact is not very well described in The Ruby
Programming Language (Flanagan, Matsumoto). Changing the first letter of
code_words to uppercase (ie Code_words) makes it into a constant that
CAN be accessed from the calling file

hey there Agent M. -

first, let me say how happy i am that you’re reading the poignant
guide - brilliant freakin book. you’ll come away with a lot.

second, another option (and perhaps better than converting the hash
into a constant,) is to put an “@” in front of code_words, (@code_words)

  • this is an instance variable, and is also accessible from the calling

    cheers, and happy reading,

    • j