Setting up global variables when hosting IronRuby in CLR

How to setup global variables in CLR that could be accessed by scripts
running in Iron Ruby engine hosted in CLR.

Some posts referred to the API Runtime.GetCurrentExecutionContext and
then setting up global variables there but in IronRuby version 1.1.3
this API is missing.

Ruby Script code (Test.rb):
class Test
def DoSomething()
puts “Value of global variable is #{$gVar}”

C# code:
// setup runtime etc
engine = runtime.GetEngine(“IronRuby”);

// setup global variables
// something like gVar = “Hello IronRuby”
scriptSource = engine.CreateScriptSourceFromFile(scriptFile)

object myType = engine.Runtime.Globals.GetVariable(“Test”);
// Create a class instance
object myTypeObj = engine.Operations.CreateInstance(myType);
// Execute method
object result = engine.Operations.InvokeMember(myTypeObj,

Any help is greatly appreciated.

Thank you,


You can still access RubyContext through
The following extension method adds the old API back … if you need

public static class IronRubyExtensions {
    public static RubyContext GetExecutionContext(this

ScriptEngine engine) {
return HostingHelpers.GetLanguageContext(engine) as

Then setting a global variable from C# is:

engine.GetExecutionContext().DefineGlobalVariable("gVar", 42);

That being said, this API isn’t final and may change in future
versions of the DLR. If you rather use an API that is more final, and
you still really need to set a global variable, you could do it by
actually executing Ruby code:

dynamic scope = engine.CreateScope();
scope.gVar = 42
engine.Execute("$gVar = gVar", scope);

Now to the address my “if you need it” comments:
Ruby.GetExecutionContext(ScriptEngine) was removed from IronRuby 1.0
as we didn’t want to promote an hosting-level API that is
language-specific. Also, because it’s main usage is for setting global
variables (since there is no DLR-level API for Ruby globals), we felt
comfortable about introducing this breaking change as using Ruby
global variables is not a recommended practice (see