如何访问 IRB 所需的 Ruby 文件中定义的变量? [英] How can I access a variable defined in a Ruby file I required in IRB?

查看:20
本文介绍了如何访问 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

这篇关于如何访问 IRB 所需的 Ruby 文件中定义的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆