Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

ruby

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

like image 688
Chris Avatar asked Feb 03 '10 13:02

Chris


People also ask

What does &: mean in Ruby?

What you are seeing is the & operator applied to a :symbol . In a method argument list, the & operator takes its operand, converts it to a Proc object if it isn't already (by calling to_proc on it) and passes it to the method as if a block had been used.

How do you find the type of an object in Ruby?

The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object. class . Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.

Is name a keyword in Ruby?

Keywords in ruby are nothing but reserved words used for some specific internal process or represent some predefined actions.No variable, Object, or constant could be named a keyword.


1 Answers

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

like image 179
bta Avatar answered Sep 19 '22 18:09

bta