Checking Object Type in Ruby

Ruby employs Duck Typing approach when working with object. Often times we don’t know what type of the object we pass to our methods since they can potentially accept any type if Duck Typing principle is preserved.

In order to check for object type in Ruby, we need to employ one of two methods.

First method for checking object type in Ruby is to check to see whether a given object respond to the method you are trying to call.

if obj.respond_to? :my_action
 my_actions = obj.my_action
else

Second method for checking object type is to see if objects of a specific class or specific module

if my_var.is_a ? Float
 raise ArgumentError, “Not a float”
else
 puts “my_var is a Float”
end

It is always preferred to use first method of checking for object type since it aligns well with generally suggested Duck Typing philosophy of the Ruby Programming Language.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…