views:

77

answers:

2

What is the difference? When should I use which? Why are there so many of them?

+6  A: 

kind_of? and is_a? are synonymous. instance_of? is different from the other two in that it only returns true if the object is an instance of that exact class, not a subclass.

Example: 5.is_a? Integer and 5.kind_of? Integer return true because 5 is a Fixnum and Fixnum is a subclass of Integer. However 5.instance_of? Integer returns false.

sepp2k
ah is `is_a?` just for backwards compatibility then?
Claudiu
It just reads better sometimes. Think `@honda.kind_of? Car` and `@person.is_a? Administrator`, Ruby's all about the aesthetics. In fact, notice the grammatical error... with active support you can write `@person.is_an? Administrator` :)... That might have made it into Ruby core by now, actually.
thenduks
heh that's an interesting reason. can you break this, thouugh? like can you override `kind_of?` but not `is_a?`?
Claudiu
+1  A: 

What is the difference?

From the documentation:

- (Boolean) instance_of?(class)
Returns true if obj is an instance of the given class.

and:

- (Boolean) is_a?(class)
- (Boolean) kind_of?(class)
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.

When should I use which?

Never. Use polymorphism instead.

Why are there so many of them?

I wouldn't call two "many". There are two of them, because they do two different things.

Jörg W Mittag
I think my confusion was that there are 3, and that 2 just do the same thing and have different names. About using polymorphism - I agree, but the ruby standard library is full of uses of each of these
Claudiu