Ruby can store different types in one array because everything is an Object

Array is a linear data structure that stores same type of data into a container. This means you cannot store different types of data into the same array.

// valid
int iarr[2] = {17, 34};
float farr[2] = {3.14, 1.59};
bool barr[2] = {true, false};
char carr[2] = {'a', 'b'};

// error: incompatible pointer to integer conversion 
// initializing 'int' with an expression of type 'char[4]' [-Wint-conversion]
int iarr[2] = {17, "abc"};

But in Ruby, it seems to be able to store different types of data in the array.

# valid
arr = [17, 3.14, true, 'a', "string", nil, method(:foo)]

It seems odd, however, all the elements inside arr are actually sharing the same data type, Object. In Ruby, everything is object including null and function. And all these objects inherit the Object class.

arr = [17, 3.14, true, 'a', "string", nil, method(:foo)]

for v in arr do
puts "'#{v.inspect}' in Object? #{v.kind_of? Object}"
end

# '17' in Object? true
# '3.14' in Object? true
# 'true' in Object? true
# 'a' in Object? true
# 'string' in Object? true
# 'nil' in Object? true
# '#<Method: Object#foo>' in Object? true

Since the array’s type is Object, it can store any data that inherits from Object class. We can simulate this behavior in strongly typed language like C/C++ using void*.