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.

Published Friday, January 09, 2009 1:04 PM by shayf
תגים:, ,

Comments

# re: IronRuby Tip: Ruby String and ClrString

As Always good post. :) Only If I can persuade my boss to let me program in dynamic language!

Monday, January 12, 2009 11:23 PM by Nadav

# re: IronRuby Tip: Ruby String and ClrString

One thing that bit me was this:

clr_string == "MyString"

=> false

Equality comparison between a ruby string and a ClrString doesn't work.

Wednesday, March 25, 2009 1:17 AM by Thomas Lundström

# Specification Testing in .NET using Ruby | The Tomes Of Experience

Pingback from  Specification Testing in .NET using Ruby | The Tomes Of Experience

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: