Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class() vs. type() in Ruby

Tags:

syntax

ruby

What's the difference between the class and type methods in Ruby? I've noticed that type works to find the type of some classes but not others.

like image 585
Chris Collins Avatar asked May 06 '09 19:05

Chris Collins


People also ask

What is a type in Ruby?

Data types in Ruby represents different types of data like text, string, numbers, etc. All data types are based on classes because it is a pure Object-Oriented language. There are different data types in Ruby as follows: Numbers. Boolean.

What is a class in Ruby?

What is a class in Ruby? Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects. Objects are the products of the class.

What is the difference between a class and a module in Ruby?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).

Is class an object in Ruby?

A class is terminated by end keyword and all the data members are lies in between class definition and end keyword. Creating Objects using the “new” method in Ruby: Classes and objects are the most important part of Ruby. Like class objects are also easy to create, we can create a number of objects from a single class.


1 Answers

The key difference is that Object#type is deprecated. From the RDoc for Object#type:

Deprecated synonym for Object#class.

Here's why you should use Object#class:

Returns the class of obj, now preferred over Object#type, as an object‘s type in Ruby is only loosely tied to that object‘s class. This method must always be called with an explicit receiver, as class is also a reserved word in Ruby.

In reality, you probably want to use Object#respond_to? instead of checking for the class of an object in most cases.

like image 194
runako Avatar answered Sep 23 '22 14:09

runako