tags:

views:

2825

answers:

2

What's the difference between the class and type methods in Ruby? I've noticed that type works to find the type of some classes but not others.

+6  A: 

#type is a synonym for #class, but it's deprecated in ruby 1.8, and apparently gone from ruby 1.9. Just use #class everywhere.


# For ruby 1.8

$ ri Object#type
------------------------------------------------------------ Object#type
     obj.type   => class
------------------------------------------------------------------------
     Deprecated synonym for Object#class.


# For ruby 1.9

$ ri1.9 Object#type
Nothing known about Object#type
kch
If it's a synonym, why would I get an undefined method error when I call type on a class I've defined myself? But the same thing does not happen when I call the class method for the same class. undefined method error doesn't sound like what you would get for a deprecated method.
Chris Collins
Are you on ruby 1.9? On ruby 1.8 I don't get an error, just a warning about the deprecation.
kch
And if you're on ruby 1.9, well, deprecation means it'll be removed some when, and looks like 1.9 is that when.
kch
I'm on 1.9, yes.
Chris Collins
+6  A: 

The key difference is that Object#type is deprecated. From the RDoc for Object#type:

Deprecated synonym for Object#class.

Here's why you should use Object#class:

Returns the class of obj, now preferred over Object#type, as an object‘s type in Ruby is only loosely tied to that object‘s class. This method must always be called with an explicit receiver, as class is also a reserved word in Ruby.

In reality, you probably want to use Object#respond_to? instead of checking for the class of an object in most cases.

runako
If it's a synonym, why would I get an undefined method error when I call type on a class I've defined myself? But the same thing does not happen when I call the class method for the same class. undefined method error doesn't sound like what you would get for a deprecated method.
Chris Collins
@Chris Collins my guess is that the doc is off, and that it's not a strict synonym. Point remains that Object#type is a no-use method.
runako
Why use respond_to?
Chris Collins
cf. duck typing.
kch
ok. Didn't know about respond_to. That's handy. Thanks.
Chris Collins
@Chris Collins to expand on @kch's comment, most of the time you want to know "Is this object capable of printing its name?" or something. So using o.class == Person is a blunt instrument in this case. Better to do o.respond_to?(:display_name), which will work on a Person, or a Dog, or a Company. Google Ruby Duck Typing for more.
runako