Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining type of an object in ruby

Tags:

types

ruby

I'll use python as an example of what I'm looking for (you can think of it as pseudocode if you don't know Python):

>>> a = 1 >>> type(a) <type 'int'> 

I know in ruby I can do :

1.9.3p194 :002 > 1.class  => Fixnum  

But is this the proper way to determine the type of the object?

like image 859
Zippy Zeppoli Avatar asked Apr 02 '13 16:04

Zippy Zeppoli


People also ask

How do you check what type an object is?

Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.

How do I find the instance of Ruby?

Use #is_a? to Determine the Instance's Class Name in Ruby If the object given is an instance of a class , it returns true ; otherwise, it returns false .

How do you define an object in Ruby?

You can create objects in Ruby by using the method new of the class. The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods. Here, cust1 and cust2 are the names of two objects.

What is NilClass in Ruby?

In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.


1 Answers

The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object.class.

Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.is_a?(ClassName) to see if object is of type ClassName or derived from it.

Normally type checking is not done in Ruby, but instead objects are assessed based on their ability to respond to particular methods, commonly called "Duck typing". In other words, if it responds to the methods you want, there's no reason to be particular about the type.

For example, object.is_a?(String) is too rigid since another class might implement methods that convert it into a string, or make it behave identically to how String behaves. object.respond_to?(:to_s) would be a better way to test that the object in question does what you want.

like image 81
tadman Avatar answered Oct 09 '22 04:10

tadman