How to Check Data Type in Ruby: Simple Syntax and Examples
In Ruby, you can check the data type of any object by calling the
.class method on it. This method returns the class name of the object, which represents its data type.Syntax
Use the .class method on any Ruby object to find out its data type. The syntax is simple:
object.class- returns the class (data type) of the object.
ruby
object.classExample
This example shows how to check the data type of different objects like a number, a string, and an array.
ruby
number = 42 puts number.class # Output: Integer text = "hello" puts text.class # Output: String list = [1, 2, 3] puts list.class # Output: Array
Output
Integer
String
Array
Common Pitfalls
Sometimes beginners expect .class to return a simple type name like 'int' or 'str' as in other languages, but Ruby returns the full class name like Integer or String. Also, .class works on objects, not on variable names directly.
Wrong way:
value = 10 puts value.class # Returns Integer puts Integer.class # This returns Class, not the type of a variable
Right way:
value = 10 puts value.class # Returns Integer
ruby
value = 10 puts value.class # Correct usage
Output
Integer
Quick Reference
| Object | Data Type Returned by .class |
|---|---|
| 42 | Integer |
| 3.14 | Float |
| "hello" | String |
| [1, 2, 3] | Array |
| {a: 1, b: 2} | Hash |
| true | TrueClass |
| nil | NilClass |
Key Takeaways
Use the .class method on any Ruby object to find its data type.
The .class method returns the object's class name, like Integer or String.
Always call .class on the object, not on the class name itself.
Common Ruby data types include Integer, String, Array, Hash, TrueClass, and NilClass.
Checking data types helps understand what kind of data you are working with.