juniorRuby

What are the differences between arrays and hashes in Ruby?

Updated May 17, 2026

Short answer

Arrays are ordered, integer-indexed collections of elements. Hashes are collections of key-value pairs where keys can be any object type, offering fast lookups based on key equality.

Deep explanation

An Array is a zero-indexed sequential collection. Accessing an element by index is an O(1) operation, but searching for an arbitrary value takes O(n) time. A Hash maps unique keys to values using a hashing algorithm. It provides near O(1) time complexity for lookup, insertion, and deletion of elements when the key is known. In modern Ruby (1.9+), Hashes also preserve their insertion order.

Real-world example

Use an array to store an ordered sequence of elements, such as a timeline of posts. Use a hash to represent configurations, dictionaries, or data attributes like a user's profile details.

Common mistakes

  • Using an array when quick lookup by a unique identifier is required, resulting in inefficient iterations using `.find` or `.any?` over a large data set.

Follow-up questions

  • What happens if you access a hash key that does not exist?
  • Can you use mutable objects like arrays as hash keys?

More Ruby interview questions

View all →