在IRB中访问环境变量,但在运行文件时没有

时间:2022-03-22 22:41:48
require 'io/console'
def test
  IO.console.winsize
end

puts "1: test: #{test()}"
puts "2: env: #{ENV['COLUMNS']}"

When I run this, this is what I see in my console:

当我运行它时,这是我在控制台中看到的:

 1: test: [23, 80]
 2: env: 

In other words, I'm not able to print out ENV['COLUMNS'] when I run the program

换句话说,当我运行程序时,我无法打印出ENV ['COLUMNS']

However, typing ENV['COLUMNS'] within IRB gives me a string equal to the terminal width.

但是,在IRB中键入ENV ['COLUMNS']会给我一个等于终端宽度的字符串。

I am wondering why this is the case.

我想知道为什么会这样。

1 个解决方案

#1


3  

Only variables that are exported by your shell will be available in a Ruby script:

只有shell导出的变量才能在Ruby脚本中使用:

$ ruby -e "puts ENV['COLUMNS']"

$ export COLUMNS
$ ruby -e "puts ENV['COLUMNS']"
80
  • this answer here presents a possible workaround (follow the first link and check out the yaml branch on Github)

    这里的答案提供了一个可能的解决方法(按照第一个链接并查看Github上的yaml分支)

  • here is an answer that presents a way to get the terminal size without using shell variables

    这是一个答案,它提供了一种在不使用shell变量的情况下获取终端大小的方法

#1


3  

Only variables that are exported by your shell will be available in a Ruby script:

只有shell导出的变量才能在Ruby脚本中使用:

$ ruby -e "puts ENV['COLUMNS']"

$ export COLUMNS
$ ruby -e "puts ENV['COLUMNS']"
80
  • this answer here presents a possible workaround (follow the first link and check out the yaml branch on Github)

    这里的答案提供了一个可能的解决方法(按照第一个链接并查看Github上的yaml分支)

  • here is an answer that presents a way to get the terminal size without using shell variables

    这是一个答案,它提供了一种在不使用shell变量的情况下获取终端大小的方法