开发者

'Require' bringing up a NameError

I've saved the following hash under file2.rb

codewords = {'starmonkeys' => 'Five edged primates.'}

*Some of you may recognize this from the Poignant Guide!

And the following under file1.rb:

if __FILE__ == $0
    require File.expand_path('C:\Users\COMPAQ\My Documents\Aptana Studio Workspace\why the lucky stiff made me do this\file2.rb', __FILE__)

    print "Enter your secret sentence."
    idea = gets

    codewords.each do | real , code|
      idea.gsub!( real , code )
    end

    #Saving to a new file
    print "File encoded. Print a file name for this idea"
    idea_name = gets.strip
    File::open( "idea-"+idea_name+".txt","w" ) do |f|
      f<<idea
    end
end

I am bringing up a NameError: file.rb:7:in <main开发者_StackOverflow社区>': undefined local variable or methodcodewords' for main:Object (NameError)

What am I doing wrong that is bringing this up?


As far as I know, variable declarations are scoped to the file they are defined in. That means they basically don't exist outside the scope of the file. To bridge that gap you might need to use a constant, a class, or a module, or a combination of those for namespacing purposes. For example:

# file2.rb

module Codewords
  CODEWORDS = { ... }
end

Later you can require and use this like this:

include Codewords

CODEWORDS.each do |real, code|
  # ...
end


you can declare codewords to be global and then access it later by referring to it as

         $codewords = {'starmonkeys' => 'Five edged primates.'} #file2.rb

Then in file1.rb:

          codewords.each do | real , code|
            idea.gsub!( real , code )
          end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜