Bud*_*Joe 16 ruby variables scope irb requires
该文件welcome.rb
包含:
welcome_message = "hi there"
Run Code Online (Sandbox Code Playgroud)
但是在IRB中,我无法访问刚刚创建的变量:
require './welcome.rb'
puts welcome_message
# => undefined local variable or method `welcome_message' for main:Object
Run Code Online (Sandbox Code Playgroud)
当您require
进入IRB会话时,引入预定义变量并完成初始化工作的最佳方法是什么?全局变量似乎不是正确的路径.
Joh*_*and 14
虽然您无法访问在必需文件中定义的局部变量,但您可以访问常量,并且可以访问存储在两个上下文中您都可以访问的对象中的任何内容.因此,根据您的目标,有几种方法可以共享信息.
最常见的解决方案可能是定义一个模块并将您的共享值放在那里.由于模块是常量,因此您可以在需要的上下文中访问它.
# in welcome.rb
module Messages
WELCOME = "hi there"
end
# in irb
puts Messages::WELCOME # prints out "hi there"
Run Code Online (Sandbox Code Playgroud)
您也可以将值放在类中,达到同样的效果.或者,您可以将其定义为文件中的常量.由于默认上下文是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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5423 次 |
最近记录: |