Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between arrays and hashes?

What's the difference between arrays and hashes in Ruby?

like image 484
emurad Avatar asked May 23 '11 13:05

emurad


People also ask

What is the difference between hashes and arrays?

With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements. It's more efficient to access array elements, but hashes provide more flexibility.

Is a hash an array?

A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. Hashes enumerate their values in the order that the corresponding keys were inserted.

Is hashing better than array?

Simply put, using a hash table is faster than searching through an array. In the Find the First Non-Repeating Character algorithm challenge, we use hash tables as an optimal solution compared to nested for loops, which is a reduction in complexity from O(n*n) to O(n).

Is hash table same as array?

Even though both array and hashtable data structure are intended for fast search i.e. constant time search operation also known as O(1) search, the fundamental difference between them is that array require an index while hash table requires a key which could be another object.


1 Answers

From Ruby-Doc:

Arrays are ordered, integer-indexed collections of any object. Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array—that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on. Look here for more.

A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. Hashes enumerate their values in the order that the corresponding keys were inserted.

Hashes have a default value that is returned when accessing keys that do not exist in the hash. By default, that value is nil. Look here for more.

like image 115
intellidiot Avatar answered Sep 20 '22 15:09

intellidiot