在运行后与 Ruby 脚本交互

Interact with Ruby script after it runs

我习惯在IPython中做以下事情:

run foo

它会加载文件 foo.py。然后文件中定义的每个变量都在范围内。现在正在学习Ruby。我有一个 hello.rb 文件,其中只有以下内容:

puts "Hello"
x = 1

当我用

在 irb 中加载它时
load './hello.rb'

终端在屏幕上打印 "Hello"。但是我不会玩变量 x.

我该怎么做?

谢谢。

在 Ruby 中,您无法访问所需文件中定义的局部变量。在 irb 文件中,局部变量超出范围。

您可以采取一些措施来解决此问题:

  • 定义常量:

    #hello.rb
    module SharedConst
    X = 1
    end
    puts "Hello"
    
    #in irb
    puts SharedConst::X
    # => 1
    
  • 定义实例变量

    #hello.rb
    puts "Hello"
    @x = 1
    
    #in irb
    @x
    # => 1