Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

question from:https://stackoverflow.com/questions/831380/class-vs-type-in-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
237 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...