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

问题描述:

文件welcome.rb包含:

welcome_message = "hi there"

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

But in IRB, I can't access the variable I just created:

require './welcome.rb'

puts welcome_message 

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

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

What is the best way to bring in predefined variables and have initialization work done when you require something into your IRB session? Global variables don't seem like the right path.

虽然确实不能访问必需文件中定义的局部变量,但是可以访问常量,也可以访问存储在具有访问权限的对象中的任何内容在这两种情况下.因此,根据您的目标,有几种共享信息的方法.

While it is true that you cannot access local variables defined in required files, you can access constants, and you can access anything stored in an object that you have access to in both contexts. So, there are a few ways to share information, depending on your goals.

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

The most common solution is probably to define a module and put your shared value in there. Since modules are constants, you'll be able to access it in the requiring context.

# in welcome.rb
module Messages
  WELCOME = "hi there"
end

# in irb
puts Messages::WELCOME   # prints out "hi there"

您也可以将值放在类中,效果大致相同.或者,您可以将其定义为文件中的常量.由于默认上下文是Object类(称为main)的对象,因此您还可以在main上定义方法,实例变量或类变量.所有这些方法最终或多或少地是产生全局变量"的本质上不同的方式,并且对于大多数目的而言可能不是最佳的.另一方面,对于范围界定得很好的小型项目,可能会很好.

You could also put the value inside a class, to much the same effect. Alternatively, you could just define it as a constant in the file. Since the default context is an object of class Object, referred to as main, you could also define a method, instance variable, or class variable on main. All of these approaches end up being essentially different ways of making "global variables," more or less, and may not be optimal for most purposes. On the other hand, for small projects with very well defined scopes, they may be fine.

# 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