如何访问IRB中所需的Ruby文件中定义的变量?

welcome.rb文件包含:

 welcome_message = "hi there" 

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

 require './welcome.rb' puts welcome_message # => undefined local variable or method `welcome_message' for main:Object 

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

虽然您无法访问在必需文件中定义的局部变量,但您可以访问常量,并且可以访问存储在两个上下文中您都可以访问的对象中的任何内容。 因此,根据您的目标,有几种方法可以共享信息。

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

 # 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 

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

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

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

 class Welcome MESSAGE = "hi there" end 

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

 puts Welcome::MESSAGE 

这应该至少能够从irb获得经验:

 def welcome_message; "hi there" end