Ironing code, geek t-shirts and even presentations!


Executing IronPython Code from IronRuby

One of the advantages of the Dynamic Language Runtime (DLR) is the fact that it makes sharing code between the languages that are written on top of it (and on top of the CLR as well). Therefore, it is possible to share code between IronPython and IronRuby (and any other DLR language as well like IronScheme).

This means that IronPython libraries can be used from IronRuby code and vice versa. Ruby on Rails in Python? Django in Ruby? feels like the end of days, isn’t it? perhaps we should really start preparing to year 2012

In this post I’ll show you how to run simple IronPython code from IronRuby so you can take it and do whatever your imagination guides you to.

Assuming we have a IronPython file with the next content:

class MyPythonClass:
  def add(self, x, y):
    return x + y

welcome_message = "Hello from Python!"


To those of you who don’t know Python, the code  above declares a class named MyPythonClass with a single method named add that combines two numbers and return the result. It also contains a variable named welcome_message.


Because executing Python code from IronRuby involves DLR services, methods that you call from IronRuby must have self as their first argument just like IronRuby-targeted C# methods have (if the method accepts no parameters, then it should have only the self argument). This argument contains the caller class instance.
This means that python code that should be executed by IronRuby should be modified to match the requirements.

After we have the python file in place we can use it from IronRuby. The key for doing so is loading the python file using the IronRuby.require method. This method is similar to the Kernel#require method but with a small difference – it returns the DLR scope object of the loaded script.  This enables you to call the script members via the scope, just like when you load a script manually via the DLR LoadFile method.

The next IronRuby is pretty straight-forward:

# Load the python file
python = IronRuby.require('')

# Get an instance of MyPythonClass
python_class = python.MyPythonClass()
# Execute the add method (pay attention that there's no 
# need to pass the self parameter, this is done automatically)
puts python_class.add(1, 5)

# Get the python variable and print its value
puts python.welcome_message
# Set the python variable
python.welcome_message = "Hello from Ruby!"
# Print its new value
puts python.welcome_message


The output is:
Hello from Python!
Hello from Ruby!

Note that for this sample to run, you need IronRuby and IronPython installed on your machine, both compiled with the same Microsoft.Scripting project. I just compiled IronRuby’s and IronPython’s sources to make  it work.

In conclusion, the DLR opens a bunch of new and exciting possibilities specifically in the field of code sharing between dynamic languages and dynamic and static languages. Go ahead and try it, it’s magical!

All the best,

kick it on Shout it

C# Recorder using IronRuby

[This post is the second in my series of IronRuby samples. Read the first one here]

The release of Visual Studio 2010 Beta 2 and IronRuby .Net 4.0 Beta 2 CTP has brought some AMAZING abilities to the .Net world like the dynamic keyword. This keyword is a revolutionary little thing. It takes everything you know about C# and throws it away – explicit types, locating syntax errors in compilation time, compiled code…

Sounds bad? well, it is just AWESOME!!! The dynamic keyword brings so much goodness to our beloved C# language, that if it was possible I would have hugged it and asked it to join my family.

Well, enough with the nonsense, let’s get down to business. IronRuby is Microsoft’s implementation of the Ruby language. It runs on top of the DLR and provides a seamless integration with .Net code. In short, it ROCKZZZZZ. This post is about IronRuby’s seamless integration with .Net and the ability to use the great power of Ruby inside C#.

The Ruby language has some very powerful metaprogramming abilities. One of those is the method_missing method. When you declare it in your class, every call to a method that doesn’t exist will be routed to it. You can then do whatever you want with the call – execute a different method, raise an exception, interpret the call somehow or just do whatever you want (jump in the air? do your little Irish dance thing?).

Another nice metaprogramming feature is the ability to send requests to objects by using the send method. The concept is very similar to C#’s reflection method – Invoke.

Now if we combine method_missing and send, we can create a class that saves calls and playbacks them upon request. I will call it… tam tam tam… Recorder:


class Recorder
  # Initialize an array that will save the calls
  def initialize
    @calls = []
  # Save the calls to method_missing	
  def method_missing(name, *args, &block)
    @calls << [name, args, block]

  # Playback the calls on a given object	
  def playback(obj)
    @calls.each do |name, args, block|
      obj.send name, *args, &block


I think this code is pretty straight forward, no special things here. With this class defined, we can record Ruby calls and playback them on Ruby objects:


# Record calls
rec =
rec.insert 2, "ABAB"
rec.delete! "A"

# Playback them on a real object
str = "Hello World"
puts str # Prints "dlBBroW olleH" 



It is AWESOME, but the great thing about it is that with .Net 4.0 and the dynamic keyword, it is available in C# too!

To try the next code by yourself, first open Visual Studio 2010 Beta 2, create a new C# console application and add references to IronRuby.dll, IronRuby.Libraries.dll, Microsoft.Scripting.dll and Microsoft.Dynamic.dll (remember to use the CTP assemblies and not the regular IronRuby assemblies).

The following code loads the Ruby recorder class file (recorder.rb) to the C# environment, creates an instance of the Recorder class, records a few operations and playbacks them on .Net objects:


static void Main(string[] args) 
  // Load the recorder IronRuby file
  var engine = IronRuby.Ruby.CreateEngine();
  dynamic ruby = engine.Runtime.Globals;

  // Initialize IronRuby's recorder class
  dynamic recorder = ruby.Recorder.@new();

  // Record

  // Playback on CLR's List object
  List<int> list = new List<int>();

  // Print the results!
  foreach (var item in list)

  // Record console printing
  recorder = ruby.Recorder.@new();
  recorder.WriteLine(" and .Net 4.0");

  // Playback on console

The output to the console will be:
IronRuby and .Net 4.0

Try it out and see the magic happens right in front of your very own eyes!

In my opinion, this joint venture is incredibly helpful and useful. I predict that as time goes by we will see more and more dynamic language code make its way to the conservative .Net world, enhancing it and adding it powerful abilities that it never has had before.

All the best,

Share it: kick it on Shout it

Make Your Application Extendable Using the DLR

It’s very common for applications to have a way to extend them. Extensibility comes in various ways and have multiple names too – plug-ins, add-ins, addons, etc. It seems, though, that one kind of extensibility was left to the very few – application macros.
The concept is very simple – You don’t need to create a special Dll, implement a specific interface and register it somehow, you don’t even have to install an IDE. All you have to do is to open the relevant window, write some code and voila – you’ve extended the application.

What is this post about?

I’ll start with the result.
I built a simple application – it has a textbox, a “Send” button and a larger textbox for the application output. The flow is very simple – the user writes text in the textbox, hits “Send” and a “Hello” message appears in the larger textbox:

Extending Applications using the DLR - Sample #1

The power lies in the button on the bottom of the form - “Extensions”. Clicking there will open the extensions dialog, where you can write a macro which will be run after the user clicks “Send”. The users can choose the language for their macro, which will be one of the DLR’s languages – IronRuby or IronPython. After the user writes the code and hits “Save”, the application is extended!

Extending Applications using the DLR - Sample #2


Now when the user clicks send, look what happens:

Extending Applications using the DLR - Sample #3

This sample is very simple but it took me about 20 minutes to get it done. It’s just magic!

How was it done?

Well, all the credit goes to the DLR. This amazing little thing, makes it soooo easy to integrate dynamic languages into the .Net environment, that it’s a shame not to do so.

The heart of this application is the ExtensionRunner class and its Run method:

public static bool Run(Form1 frm, string code, bool rubyCode)

The method receives 3 parameters – the form object to pass to the executed code, the code that the user has written and a boolean value indicating whether it’s ruby or python code.

Firstly, I declare a ScriptScope and a ScriptEngine variables and fill them with the chosen language implementation. Because all DLR languages implement the same interfaces and classes, this is the only language-related code here. After that, the code will fit every DLR language. This means that adding IronScheme and Nua here, for instance, will be a matter of seconds:

scope = null; ScriptEngine engine = null; if (rubyCode) { engine = Ruby.CreateEngine(); scope = Ruby.CreateRuntime().CreateScope(); } else { engine = Python.CreateEngine(); scope = Python.CreateRuntime().CreateScope(); }

Now we declare variables that the macro code will be able to use. We declare 2 variables:

  • frm – which is the form object. you wouldn’t want to do that in your application, the right way will be to pass a class with targeted functionality for the extensions.
  • return_value – the extension will put a value here. It’s a boolean value which indicates whether we should continue with the regular flow of the application after the extension has been executed or stop.

"frm",frm); scope.SetVariable("return_value", false);

The rest of the code is pretty straight forward – I create a ScriptSource object from the given code and execute it. Then I get the return_value value and return it to my main application.

// Run the code!
ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements); source.Execute(scope); // Get the return value bool retVal = scope.GetVariable<bool>("return_value"); return retVal;

This is it. The other code of the application is just a regular WinForms code so I won’t deep dive into it.


In conclusion, the DLR makes it very simple to run dynamic languages from your .Net code. I showed you here only one of the possibilities that are made available with this kind of integration.

Go ahead and try!

Download the source code

All the best,

Like it? Share it: Loves soccer? Kick it  | Angry? Shout it  | In DA ZONE? DZone it

IronRuby, IronPython and DLR Daily Builds RSS Feed Is Available!

With the help of Harry Pierson (AKA DevHawk), there is an RSS feed that will notify you when a new nightly build is available!image 
The builds are daily and you get the latest versions of IronRuby, IronPython and the DLR in Silverlight or desktop versions.

So all of you early adapters, go ahead and subscribe to the feed!

Comment: the files in the feed are the built files, not the source code.


Getting Started With Dynamic Languages

I've grouped together some resources and blogs for all of you out there who are willing to start working with dynamic languages that are built on top of the DLR. Enjoy!

IronRuby IronRuby


Currently you'll have to get the code from the IronRuby SVN repository (svn://  OR HTTP:// and build the project yourself.
Justin Etheredge has posted a step-by-step walk-through on his blog.


Recommended Blogs

IronPython IronPython


You can get the installer from the IronPython codeplex homepage:


Recommended Blogs

IronScheme  IronScheme


You can get the installer from:


The Dynamic Language Runtime DLR - The Dynamic Language Runtime

There is no need to download the DLR code separately because it already comes with the installation of the other languages. If you want to write your own language on top of the DLR, this is the place to start for you.


You can get the binaries and the code from the codeplex homepage:


Hope it helps,

kick it on