- Posted by Shay Friedman on October 22, 2009
A bunch of readers have asked me to post IronRuby samples. I took your advice and I am starting a series of posts where I’ll write some IronRuby samples so you can see what’s IronRuby code is all about.
I’ll begin with the simplest sample and as the series goes on, I’ll try to bring you more complex samples. If you’d like to see a specific sample, please contact me and let me know about it.
So the first sample is a Hello World sample. The regular Ruby Hello World app, which of course runs on IronRuby as well, is as follows:
Now, the great thing about IronRuby is the ability to use .Net classes. The next code also writes Hello World to the console, but this time it uses .Net’s System.Console class. The sample also sets the color of the text to green:
orig_color = System::Console.foreground_color
System::Console.foreground_color = System::ConsoleColor.green
System::Console.write_line "Hello World"
System::Console.foreground_color = orig_color
To run that, just save this text into a file and execute it by ir.exe <file name>. This is how its execution will look like:
.Net developers pay attention - CLR objects get Ruby’s naming conventions when they are converted to IronRuby objects. This operation is called “name mangling”. This is why System.Console.ForegroundColor appears as System::Console.foreground_color in IronRuby. You can read more about name mangling in the .Net Interoperability Fundamentals chapter in my book. These chapters are available for free through the Rough Cuts program.
If you’d like to see a certain sample next time, let me know.
All the best,