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
2010-10-08 18:30:59
ah is `is_a?` just for backwards compatibility then?
Claudiu
2010-10-08 18:43:39
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
2010-10-08 19:18:25
heh that's an interesting reason. can you break this, thouugh? like can you override `kind_of?` but not `is_a?`?
Claudiu
2010-10-08 19:38:51
+1
A:
What is the difference?
From the documentation:
- - (Boolean)
instance_of?(class)
- Returns
true
ifobj
is an instance of the given class.
and:
- - (Boolean)
is_a?(class)
- (Boolean)kind_of?(class)
- Returns
true
ifclass
is the class ofobj
, or ifclass
is one of the superclasses ofobj
or modules included inobj
.
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
2010-10-08 18:44:14
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
2010-10-08 18:56:47