Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data structure are Ruby arrays?

Tags:

arrays

ruby

I am learning about Arrays and Linked List in my computer science class. My professor says that Arrays cannot have elements added or removed from the end so instead we use linked list.

I know the implementation of Arrays in Python, Ruby, and JavaScript all allow me to modify an arrays length all I want. Do these languages really implement a linked list or some other data structure and call it an array?

What is going on under the hood? And if it is not a true array, why do they call it one?

like image 808
chopper draw lion4 Avatar asked Oct 07 '14 15:10

chopper draw lion4


People also ask

What type of data structure is an array?

An array is a linear data structure that collects elements of the same data type and stores them in contiguous and adjacent memory locations. Arrays work on an index system starting from 0 to (n-1), where n is the size of the array.

What are data structures in Ruby?

A data structure is a specific way to organize & access data. Examples include: Arrays. Binary trees.

What are arrays in Ruby?

Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by an index. Array indexing starts at 0, as in C or Java.

Is array a data type in Ruby?

The following are the basic data types recognised in Ruby: Arrays. Hashes. Boolean.


1 Answers

Fixed-sized arrays cannot have elements added to the end if the array is full, but removing elements is fine. That's how a stack works.

Internally Ruby arrays are allocated as C-style arrays of a fixed size and are automatically resized as elements are added. As an optimization they are often re-sized a bit beyond what you need to avoid re-allocating on every single addition.

A linked-list is a different data structure that allows for more flexible insertion and removal, but is much slower to traverse and doesn't permit easy random access, things very important for an array structure.

like image 113
tadman Avatar answered Sep 26 '22 00:09

tadman