Is there a Ruby equivalent for the typeof reserved word in C#?

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?.

Leave a Comment