Kaleem Ullah's Blog

Class of an object

Posted in Ruby by Kaleem Ullah on January 28, 2011

In ruby, There are commonly 3 ways to test the class of an object.

1) instance_of?(class)
It will only test the immediate class of object.

n = 1
n.instance_of?(Fixnum) #=> true
n.instance_of?(Object) #=> false because Object is superclass of 'n' not the immediate one.

2) is_a?(class) OR kind_of?(class)
Both is_a? and kind_of? will return true if object belongs to immediate class or superclass.

n = 1
n.is_a?(Fixnum) #=> true
n.kind_of?(Fixnum) #=> true
n.is_a?(Object) #=> true

3) ===
Same like is_a? but different in syntax as this one’s look good from readability point of view.

Fixnum === 1 #=> true

Important thing is === is non-commutative

1 === Fixnum #=> false

That’s it.

Tagged with: , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: