Data Types in Ruby
Explore Ruby's core data types including String, Integer, Float, Boolean, Nil, Symbol, Array, and Hash.
What Are Data Types?
A data type tells Ruby what kind of value a variable holds and what operations are valid on it. In Ruby, everything is an object — even integers and booleans.
1. Everything Is an Object
Unlike many languages, Ruby has no primitive types. Every value is an instance of a class.
Built-in Data Types
Ruby's built-in scalar types are Integer, Float, String, TrueClass/FalseClass (Boolean), NilClass, and Symbol.
1. Integer
Whole numbers of any size. Ruby automatically handles big integers.
2. Float
Decimal numbers following the IEEE 754 double-precision standard.
3. String
Sequences of characters. Double-quoted strings support interpolation; single-quoted strings are literal.
4. Boolean (TrueClass / FalseClass)
Ruby has `true` and `false`. They are singleton instances of `TrueClass` and `FalseClass`.
5. Nil (NilClass)
`nil` represents the absence of a value. It is Ruby's equivalent of `null` or `None`.
6. Symbol
Symbols are immutable, reusable identifiers starting with `:`. They are more memory-efficient than strings for keys.
Collection Data Types
Ruby's built-in collection types are Array (ordered list), Hash (key-value pairs), and Range (a sequence between two values).
1. Array
An ordered, indexed list of any objects.
2. Hash
A collection of key-value pairs. Keys are usually symbols.
3. Range
A Range represents a sequence between a start and end value.
Printing the Data Type
Ruby provides `.class`, `.is_a?`, `.kind_of?`, and `.instance_of?` to inspect and verify types at runtime.
1. .class
`.class` returns the class (type) of any object.
2. is_a? / kind_of? / instance_of?
These methods check whether an object belongs to a type or its ancestors.
Type Conversion
Ruby provides explicit conversion methods like `to_i`, `to_f`, `to_s`, `to_a`, and `to_sym` to convert between types.
1. Explicit Conversion Methods
Use `to_i`, `to_f`, `to_s`, `to_a`, `to_sym` to convert between types.
2. Strict Conversions (Integer(), Float())
`Integer()` and `Float()` are strict — they raise an error if the string is not a valid number.