【问题标题】:what is the possible reason for require a file but it did not run需要文件但没有运行的可能原因是什么
【发布时间】:2011-01-13 10:03:47
【问题描述】:

可能的原因是什么?

#wordlist.rb
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'
}


irb(main):001:0> require 'wordlist.rb'
=> true
irb(main):002:0> code_words
NameError: undefined local variable or method `code_words' for main:Object
    from (irb):2
    from :0

【问题讨论】:

    标签: ruby require


    【解决方案1】:

    Kernel#load 的文档说

    在任何情况下,任何本地 加载文件中的变量是 传播到加载环境。

    正如 piyush 所说,全局或常量很好。

    【讨论】:

      【解决方案2】:

      将其声明为常量或全局变量。 code_words 存在于 require 的范围内,并且在加载后死亡/不可访问。

      【讨论】:

        猜你喜欢
        • 2016-10-27
        • 2020-10-16
        • 1970-01-01
        • 1970-01-01
        • 2019-08-17
        • 1970-01-01
        • 2013-02-16
        • 2021-09-01
        • 2012-01-01
        相关资源
        最近更新 更多