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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
804edd45d47f376ce6bb0d44e3f84fc5?d=identicon&s=25 Agent Mulder (datura)
on 2011-06-07 00:36
Hello,

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
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'
}

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
file.

  cheers, and happy reading,

  - j
This topic is locked and can not be replied to.