如何访问 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 会议中有什么内容吗?全局变量似乎不是正确的路径。
The file welcome.rb
contains:
welcome_message = "hi there"
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
虽然您确实无法访问所需文件中定义的局部变量,但您可以访问常量,并且可以访问存储在您在两个上下文中都有权访问的对象中的任何内容。因此,根据您的目标,有几种共享信息的方法。
最常见的解决方案可能是定义一个模块并将您的共享值放入其中。由于模块是常量,因此您将能够在需要的上下文中访问它。
您还可以将值放入一个类中,以达到相同的效果。或者,您可以将其定义为文件中的常量。由于默认上下文是 Object 类的对象(称为 main),因此您还可以在 main 上定义方法、实例变量或类变量。所有这些方法最终或多或少都是本质上不同的创建“全局变量”的方法,并且对于大多数目的来说可能不是最佳的。另一方面,对于范围非常明确的小型项目来说,它们可能没问题。
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.
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.
您无法访问包含文件中定义的局部变量。您可以使用伊瓦尔:
You can't access local variables defined in the included file. You can use ivars:
这至少应该能够提供 irb 的体验:
That should at least enable the experience from irb:
我认为最好的方法是定义一个这样的类
,然后在 irb 中你可以这样调用你的代码:
I think the best way is to define a class like this
then in irb you can call your code like this :