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

39,717

Solution 1

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.

Solution 2

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

Solution 3

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
Share:
39,717
Chris
Author by

Chris

I am just trying to get a badge for filling all this out.

Updated on July 30, 2022

Comments

  • Chris
    Chris almost 2 years

    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))

  • Chris
    Chris over 14 years
    It looks like s.Class is more like CustomClassInstance.GetType() and not really like typeof(CustomClass) ... am I mistaken?