views:

80

answers:

3

How to extract a name of the class from its object?

For example I have a @list object which I know is surely an instance of List class. But how do I extract that directly in code?

+4  A: 

This kind of information is rather basic Ruby programming. The answer is:

object.class

Extra tip for the next time: try finding this information yourself in the core library documentation. You know you have some kind of object, just start reading the documentation and you will find some method that suites your needs. Information about the methods you can perform on an object can be found here.

Edwin V.
+2  A: 

If you want to test for an instance of a specific class, I'd go with something like:

@list.is_a?(List)
Barry Hess
this one is not entirely correct since is_a? returns true for all ancestor classes too, so `@list.is_a?(Object)` returns true as well
Eimantas
What's wrong with that? If you have a List, it returns true. If you have a subclass of a List, it also returns true. Seems proper in either case.
Barry Hess
A: 

Like Edwin said, object.class will give you the corresponding Class object. If you just want the name of the class, use object.class.name.

Mirko Froehlich