Changing variables at runtime

Have you ever wanted to make changes to a running ruby script without having to restart? It turns out we can ;–)

Have a look at this simple script:

#!/usr/bin/env ruby
# var_at_runtime.rb
require 'irb'

# catch when users hits ctrl-c
trap 'INT' do
  IRB.start
end

loop do
  if @new_var
    puts "@new_var was set to #{@new_var}"
    break
  end
  sleep 1
end

Note the irb library, which allows us to start an irb session from within our script. After chmod u+x var_at_runtime.rb, run the script with ./var_at_runtime.rb. Hit ctrl-c to start irb (you will see the familiar >>), set the variable with @new_var = 1234, and quit to return to the running script. Sure enough, the script now has access to the local variable we set through irb.

blog comments powered by Disqus