【问题标题】:How can I access a variable defined in a Ruby file I required in IRB?如何访问在 IRB 中需要的 Ruby 文件中定义的变量?
【发布时间】:2010-04-23 14:27:23
【问题描述】:

文件welcome.rb 包含:

welcome_message = "hi there"

但是在 IRB 中,我无法访问我刚刚创建的变量:

require './welcome.rb'

puts welcome_message 

# => undefined local variable or method `welcome_message' for main:Object

当您require 某些东西进入您的 IRB 会话时,引入预定义变量并完成初始化工作的最佳方法是什么?全局变量似乎不是正确的路径。

【问题讨论】:

    标签: ruby variables scope irb requires


    【解决方案1】:

    虽然您确实无法访问在所需文件中定义的局部变量,但您可以访问常量,并且可以访问存储在对象中的任何内容,您可以在这两种上下文中访问。因此,有几种方法可以共享信息,具体取决于您的目标。

    最常见的解决方案可能是定义一个模块并将您的共享值放入其中。由于模块是常量,因此您可以在需要的上下文中访问它。

    # in welcome.rb
    module Messages
      WELCOME = "hi there"
    end
    
    # in irb
    puts Messages::WELCOME   # prints out "hi there"
    

    您也可以将值放在一个类中,效果大致相同。或者,您可以将其定义为文件中的常量。由于默认上下文是 Object 类的对象,称为 main,因此您还可以在 main 上定义方法、实例变量或类变量。所有这些方法最终都会或多或少地成为制作“全局变量”的不同方式,并且对于大多数目的而言可能不是最佳的。另一方面,对于范围非常明确的小型项目,它们可能没问题。

    # in welcome.rb
    WELCOME = "hi constant"
    @welcome = "hi instance var"
    @@welcome = "hi class var"
    def welcome
      "hi method"
    end
    
    
    # in irb
    # These all print out what you would expect.
    puts WELCOME
    puts @welcome
    puts @@welcome
    puts welcome
    

    【讨论】:

    • 很好,作为评论:John Hyland 代码中的WELCOME 可以访问,因为它以 upcase 字母开头,这使它成为一个常量。红宝石是兴趣。
    【解决方案2】:

    您无法访问包含文件中定义的局部变量。您可以使用 ivars:

    # in welcome.rb
    @welcome_message = 'hi there!'
    
    # and then, in irb:
    require 'welcome'
    puts @welcome_message
    #=>hi there!
    

    【讨论】:

      【解决方案3】:

      这至少应该能够实现来自 irb 的体验:

      def welcome_message; "hi there" end
      

      【讨论】:

        【解决方案4】:

        我认为最好的方法是定义一个这样的类

        class Welcome
          MESSAGE = "hi there"
        end
        

        然后在 irb 你可以这样调用你的代码:

        puts Welcome::MESSAGE
        

        【讨论】:

          猜你喜欢
          • 2019-12-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-21
          • 1970-01-01
          • 2019-06-20
          • 2014-12-13
          相关资源
          最近更新 更多