Ironing code, geek t-shirts and even presentations!


IronRuby Tip: Using Generic CLR Methods from IronRuby

A while ago I wrote a post about using Generic CLR classes from IronRuby. This time I’ll share with you its less intuitive friend – using generic CLR methods from IronRuby.

As a result of Ruby being a duck-typed language which works with types implicitly, generics is not really needed. The whole language is generic… This is why using generic CLR types might become a bit odd for the language. Nonetheless, this fact will not stop us. The price to pay in order to enjoy Ruby in the .Net framework is worth it! :)

Anyway, assuming we have the following C# class defined in file sample.dll:

namespace ClassLibrary1
    public class Class1
        public string Test<T>(T param)
                return param.ToString();

In order to use it with a specific type, you need to do two things – get the generic method object (by using the method method) and provide it with the type via the special of method. For example, the next code invokes Test with a string and pass it “Shay Friedman”:

require "sample.dll"

sample =
sample.method(:test).of(String).call("Shay Friedman") # returns "Shay Friedman"

And that’s all there is to know.

All the best,

Tip: How To Use Generic .Net Classes in IronRuby

In the latest version of IronRuby (0.3), the ability to use Generic .Net classes was added. I couldn’t find anywhere how to do that so I dug it out of the code and now I’ll share it with you!

Example #1 - List

This is how to define an Int32 list, add two numbers to it and print them:

list = System::Collections::Generic::List[System::Int32].new

list.add 4
list.add 12

list.each { |x| puts x }

Of course we can also use Ruby type like Numeric, String, etc.

Example #2 – Dictionary

This is how to declare a number-string dictionary, add values to it and print them:

dict = System::Collections::Generic::Dictionary[Fixnum, String].new

dict.add 1, "Hey"
dict.add 15, "There"

dict.each { |x| puts "#{x.key} - #{x.value}" }


All the best,