Forum: Ruby why's (poignant) Guide to Ruby - code question

804edd45d47f376ce6bb0d44e3f84fc5?d=identicon&s=25 Agent Mulder (datura)
on 2011-06-07 00:36

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?
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2011-06-07 01:20
Post an example program that is no longer than 5 lines that demonstrates
the problem.  Also state what what directory each file is in.
804edd45d47f376ce6bb0d44e3f84fc5?d=identicon&s=25 Agent Mulder (datura)
on 2011-06-07 01:31
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
5e3ddca8ea910cea06245c7b3c38007a?d=identicon&s=25 jake kaiden (lljk)
on 2011-06-07 19:08
hey there Agent Mulder -

  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
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.