Hash vs Array in Ruby: Key Differences and When to Use Each
Hash stores key-value pairs allowing fast lookup by keys, while an Array holds ordered lists of elements accessed by index. Use Hash when you need to associate unique keys with values, and Array when order and position matter.Quick Comparison
Here is a quick side-by-side look at the main differences between Hash and Array in Ruby.
| Factor | Hash | Array |
|---|---|---|
| Data Structure Type | Key-value pairs | Ordered list of elements |
| Access Method | By unique key | By numeric index |
| Order | Preserves insertion order (Ruby 1.9+) | Always ordered |
| Duplicates | Keys are unique, values can repeat | Elements can repeat |
| Use Case | Lookup by key, dictionary-like | Sequence, list, stack, queue |
| Performance | Fast key lookup (average O(1)) | Fast index access (O(1)) |
Key Differences
A Hash in Ruby is a collection of unique keys mapped to values. You use keys to quickly find the associated value. Keys can be symbols, strings, numbers, or any object that implements hash and eql?. Hashes preserve the order in which pairs are added starting from Ruby 1.9.
On the other hand, an Array is an ordered list of elements accessed by their position index starting at zero. Arrays allow duplicates and are best when order and sequence matter, like storing a list of items or iterating in order.
While both can store multiple items, the main difference is how you access them: Hash uses keys for direct lookup, making it ideal for dictionary-like data, whereas Array uses numeric indexes, making it ideal for ordered collections.
Code Comparison
person = { name: "Alice", age: 30, city: "NY" }
puts person[:name]
puts person[:age]
fruits = ["apple", "banana", "cherry"]
puts fruits[0]
puts fruits[2]Array Equivalent
person = ["Alice", 30, "NY"] puts person[0] # name puts person[1] # age
When to Use Which
Choose a Hash when you need to associate unique keys with values and want fast lookup by those keys, such as storing user attributes or configuration settings. Use an Array when you need to keep items in order, allow duplicates, or process elements by position, like a list of tasks or a sequence of events.
In short, use Hash for key-based access and Array for ordered collections.
Key Takeaways
Hash for fast key-value lookups with unique keys.Array for ordered lists where position matters.