Bratish Goswami

Personal website and blog

A question that comes up a lot for new Ruby developers - when should you use arrays vs hashes? Let me break it down with practical examples.

Arrays - Ordered Lists

Arrays are indexed collections. You access elements by their position (starting from 0).

fruits = ["apple", "banana", "orange"]
puts fruits[0]  # => "apple"
puts fruits[1]  # => "banana"

Hashes - Key-Value Pairs

Hashes are indexed by keys, not positions. Keys can be strings, symbols, or any object.

person = {"name" => "John", "age" => 25, "city" => "Mumbai"}
puts person["name"]  # => "John"
puts person["age"]   # => 25

When to use Arrays:

  • When order matters
  • When you need to iterate in sequence
  • When you're dealing with lists of similar items
# Good use of arrays
todo_list = ["Buy milk", "Call mom", "Write code"]
scores = [95, 87, 92, 78]

When to use Hashes:

  • When you need to look up values by meaningful keys
  • When you're dealing with attributes of an object
  • When order doesn't matter (though Ruby 1.9+ maintains insertion order)
# Good use of hashes
config = {
  "database" => "mysql",
  "host" => "localhost",
  "port" => 3306
}

user = {
  :name => "Priya",
  :email => "priya@example.com",
  :role => "admin"
}

Performance Notes:

  • Hash lookups are O(1) - constant time
  • Array lookups by index are O(1)
  • Finding an element in an array is O(n) - linear search

Common patterns:

# Array of hashes
users = [
  {"name" => "John", "age" => 25},
  {"name" => "Jane", "age" => 30}
]

# Hash with array values
categories = {
  "tech" => ["Ruby", "Python", "JavaScript"],
  "sports" => ["Cricket", "Football", "Tennis"]
}

The key is to think about how you'll be accessing your data. Need to look things up by name? Use a hash. Need to preserve order and iterate sequentially? Use an array.