Ruby arrays can hold multiple data types
Ruby arrays appear to store different data types, but under the hood, they actually store references to objects.
Here’s an example of a Ruby array containing various types:
def foo()
'function'
end
list = [17, "seventeen", 1.7, true, false, foo, nil]
This is perfectly valid Ruby code. But how does Ruby allow this?
Unlike arrays in statically-typed languages like C or C++, where arrays are strictly typed, Ruby arrays are dynamic. Rather than storing raw values directly, a Ruby array holds references to objects, allowing it to contain elements of different types (we can simulate the same behavior in C using pointers (250201115105)).
Everything in Ruby is an object—even primitive values like integers (Integer
), booleans (TrueClass
/FalseClass
), and nil
(NilClass
).
Let’s verify this by checking the class of each element:
list.each { |elem| puts elem.class }
# --- output
# Integer
# String
# Float
# TrueClass
# FalseClass
# String
# NilClass
Since everything is an object, Ruby arrays store references to objects, making them flexible and dynamic.