Shell out from ruby while setting an environment variable

mislav picture mislav · Nov 28, 2011 · Viewed 10.2k times · Source

I need to shell out to a process while setting an environment variable for it. I tried this one-liner:

system "RBENV_VERSION=system ruby extconf.rb"

This syntax works in shell script but not from ruby. (Update: turns out this syntax works from ruby after all, but I failed to see its effect due to my particular use-case.)

So I'm doing this:

rbenv_version = ENV['RBENV_VERSION']
ENV['RBENV_VERSION'] = 'system'
begin
  system "ruby extconf.rb"
ensure
  ENV['RBENV_VERSION'] = rbenv_version
end

I'm forced to such a long expression because I don't want to override the environment variable permanently if it already had a value.

Anything shorter that comes to your mind?

Answer

Avdi picture Avdi · Nov 28, 2011
system({"MYVAR" => "42"}, "echo $MYVAR")

system accepts any arguments that Process.spawn accepts.