tags:

views:

703

answers:

4

I have a C# method that I need to call from a piece of Ruby that requires a System.Type argument. Is there a Ruby equivalent to typeof in C#? The call will look something like this in C# ...

var CustomClasInstance = Container.GetInstance(typeof(ICustomClass))

A: 

For a reference on how to identify variable types in Ruby, see http://www.techotopia.com/index.php/Understanding_Ruby_Variables#Identifying_a_Ruby_Variable_Type

If you have variable named s, you can retrieve the type of it by invoking

s.class
jsalonen
It looks like s.Class is more like CustomClassInstance.GetType() and not really like typeof(CustomClass) ... am I mistaken?
Chris
+4  A: 

In addition to checking Object#class (the instance method class on the Object aka Base class), you could

s.is_a? Thing

this will check to see if s has Thing anywhere in its ancestry.

RyanWilcox
A: 
ICustomClass.to_clr_type
dtb
A: 

Either Object.class or Object.type should do what you need.

Also, the two methods Object.is_a? and Object.instance_of? can be used. However, they are not 100% identical. The statement obj.instance_of?(myClass) will return true only if object obj was created as an object of type myClass. Using obj.is_a?(myClass) will return true if the object obj is of class myClass, is of a class that has inherited from myClass, or has the module myClass included in it.

For example:

x = 1
x.class                   => Fixnum
x.instance_of? Integer    => false
x.instance_of? Numeric    => false
x.instance_of? Fixnum     => true
x.is_a? Integer           => true
x.is_a? Numeric           => true
x.is_a? Fixnum            => true

Since your C# method requires a very specific data type, I would recommend using Object.instance_of?.

bta