2011-07-06 20 views
1

我已經下file2.rb「需要」引進了一個NameError

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

保存以下哈希*你們有些人可能從悽美指南認識到這一點!

而下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 

我帶了一個NameError:file.rb:7:<main>': undefined local variable or method碼字主:對象(NameError)

我是什麼做錯了,這是帶來了嗎?

回答

2

據我所知,變量聲明的範圍是它們定義的文件。這意味着它們基本上不存在於文件範圍之外。爲了縮小這種差距,您可能需要使用常量,類或模塊或其組合來實現命名空間。例如:

# file2.rb 

module Codewords 
    CODEWORDS = { ... } 
end 

稍後,您可以要求和使用本這樣的:

include Codewords 

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

嗯謝謝...你可以向下滾動一下多一點,進入這個頁面http://mislav.uniqpath.com/poignant-guide/book/chapter-4.html下的副標題,說:「你的Replic性得到回報」並告訴我爲什麼作者聲稱它在那裏工作?或者我不能在新版Ruby版本中使用那樣的require?謝謝。 – HareKrishna

+1

@HareKrishna:你不是第一個遇到這個問題的人:http://www.falsepositives.com/index.php/2005/09/12/getting-rubys-require-to-work-in-the -poignant-guide-to-ruby/ – zetetic

+0

zeteic,這個鏈接確實有幫助。查找固定副本的尖銳指南是很有挑戰性的,儘管因爲很多鏡子都倒閉了。讓我知道你是否知道一個。這就是說,這解決了我的問題,並多一點點! – HareKrishna

0

你可以聲明碼字是全球性的,然後後來將其稱爲

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

然後在file1.rb中:

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