【问题标题】:'Require' bringing up a NameError'要求'提出一个 NameError
【发布时间】:2011-07-06 03:36:25
【问题描述】:

我在 file2.rb 下保存了以下哈希

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:in &lt;main&gt;': undefined local variable or methodcodewords' for main:Object (NameError)

我做错了什么导致这个问题?

【问题讨论】:

    标签: ruby debugging require


    【解决方案1】:

    据我所知,变量声明的范围仅限于定义它们的文件。这意味着它们基本上不存在于文件范围之外。为了弥合这个差距,您可能需要使用常量、类或模块,或者将它们组合起来用于命名空间。例如:

    # file2.rb
    
    module Codewords
      CODEWORDS = { ... }
    end
    

    稍后您可以像这样要求和使用它:

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

    【讨论】:

    • 嗯,谢谢...你能不能向下滚动到这个页面的一半以上mislav.uniqpath.com/poignant-guide/book/chapter-4.html,在“你的重复性得到回报”的副标题下,告诉我为什么作者声称它在那里工作?或者我不能在较新的 Ruby 版本中使用这样的需求?谢谢。
    • @HareKrishna:你不是第一个遇到这个问题的人:falsepositives.com/index.php/2005/09/12/…
    • zeteic,那个链接真的很有帮助。事实证明,寻找痛苦指南的固定副本具有挑战性,因为很多镜子都坏了。如果你知道,请告诉我。话虽这么说,这解决了我的问题,而且还有更多!
    【解决方案2】:

    您可以将代码字声明为全局,然后通过将其引用为以后访问它

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

    然后在file1.rb中:

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

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      相关资源
      最近更新 更多