IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

IronRuby Tip: Ruby String and ClrString

When you use IronRuby to execute some C# code, for example, and the C# code returns a string, pay  IronRuby Tip: Ruby String and ClrStringattention that the string is not a Ruby string!
The type of the object you receive is ClrString. ClrString is the equivalent of System.String in IronRuby, all the System.String methods will work on ClrString objects, but Ruby’s string methods will not (and vice versa).

For example:

clr_string = MyCSharpNameSpace::MyClass.ReturnString()

clr_string.IndexOf("something") # This will work
clr_string.EndsWith("something") # This will work

clr_string[0..2] # This will NOT work
clr_string.index("something") # This will NOT work

As you can see, the System.String methods work but the Ruby string methods don’t.

What to do?

If you want to use a System.String as a Ruby string, all you have to do is call to_s! just like that:

clr_string = MyCSharpNameSpace::MyClass.ReturnString()

clr_string = clr_string.to_s # Converting the ClrString to a Ruby string

clr_string[0..2] # This will WORK!
clr_string.index("something") # This will WORK!

Just to make clear – you will not be able to use System.String methods after the conversion to a Ruby string… One language at a time, folks, one language at a time :)

All the best,
Shay.

Pingbacks and trackbacks (1)+

Add comment