Data Types
Prerequisites: Variables
Every value in Ruby has a type — which Ruby calls its class. The class decides what you can do with the value: you can multiply numbers, and you can upper-case text, but not the other way round.
The core types you'll use every day:
| Class | Example | Used for |
|---|---|---|
Integer |
42, -7 |
Whole numbers |
Float |
3.14, -0.5 |
Numbers with a decimal point |
String |
"hello" |
Text |
Symbol |
:active |
Names and labels |
TrueClass / FalseClass |
true, false |
Yes/no values |
NilClass |
nil |
"No value" |
Array |
[1, 2, 3] |
Ordered lists |
Hash |
{ name: "Ada" } |
Key-value pairs |
Example
p 42.class
p 3.14.class
p "hello".class
p :active.class
p true.class
p nil.class
p [1, 2].class
Expected output
Integer
Float
String
Symbol
TrueClass
NilClass
Array
In Ruby, everything is an object — every value, even 42 and
nil, is an instance of a class and has methods. That's why 42.class
works: class is a method you call on the number.
Types matter because values that look alike behave differently:
p "25" + "5"
p 25 + 5
"255"
30
Common mistakes
- Adding a number to a string:
"Age: " + 25raisesno implicit conversion of Integer into String (TypeError). Convert first (25.to_s) or use interpolation ("Age: #{25}").