The main way to gain the ability to call existing .NET class libraries from ruby is through an extension to ruby's require keyword. When the strong name of a CLR assembly is placed within the quotes following the keyword, that assembly's namespaces become available in a corresponding hierarchy of ruby modules.
For example, to make the core classes in the .NET framework available to ruby, you need the mscorlib and System assemblies, so you would add this to the top of your ruby file that is going to call .NET (or to another ruby file required by the one using it):
require 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86' require 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL'
Now that these assemblies are referenced, you can invoke APIs in .NET so long as they are namespace-qualified with their corresponding ruby modules. For instance the System.Collections.Generic namespace becomes System::Collections::Generic in ruby code. We could print a line out to the console using the familiar Console API:
System::Console.write_line "Hello ruby, it's your old friend .NET!"
You probably also noticed that properties and methods of CLR classes become lower cased and underscored to separate capitalized syllables, so a method named 'DoSomethingNow' in .NET becomes 'do_something_now' in Ruby.
Once you've imported a namespace of classes from a CLR library, you probably won't want to type the full module namespace. If we want to use the 'System.Uri' class from ruby, we could add the following to the same file that contains our require statements that make the mscorlib and System assemblies available:
Uri = System::Uri UriKind = System::UriKind
Now we can create instances of Uris and specify their kind with an enumeration like so:
ironruby_url = Uri.new 'http://ironruby.rubyforge.org' ironruby_wiki_url = Uri.new '/wiki', UriKind::Relative
Here's an example that shows how to create a form with a button, and respond to a click event on it:
require 'mscorlib'
require 'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
require 'System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
Application = System::Windows::Forms::Application
Form = System::Windows::Forms::Form
MessageBox = System::Windows::Forms::MessageBox
Button = System::Windows::Forms::Button
Point = System::Drawing::Point
class MyForm < Form
def initialize
self.text = "My .NET Form from Ruby"
@button = Button.new
@button.location = Point.new 150, 150
@button.text = "Click Me!"
my_click_handler = Proc.new {|sender, e| MessageBox.show 'Hello from Ruby!'}
@button.click(&my_click_handler)
self.controls.add @button
end
end
my_form = MyForm.new
Application.run my_form