Array#assoc

array.assoc(key) -> sub_array or nil
Returns: Array or nil · Updated March 13, 2026 · Array Methods
arrays searching lookup pairs

The assoc method searches an array of arrays (like a table) for the first sub-array whose first element equals the search key. It’s perfect for looking up data in simple key-value tables.

Basic Usage

# Simple lookup
table = [["a", 1], ["b", 2], ["c", 3]]
table.assoc("b")  # => ["b", 2]
table.assoc("x")  # => nil

Practical Examples

Configuration Tables

# Environment config lookup
env_config = [
  ["development", { host: "localhost", port: 3000 }],
  ["production",  { host: "example.com", port: 80 }],
  ["test",        { host: "127.0.0.1", port: 3001 }]
]

env_config.assoc("production")
# => ["production", {:host=>"example.com", :port=>80}]
commands = [
  ["new",  CreateProjectCommand],
  ["open", OpenProjectCommand],
  ["save", SaveCommand],
  ["exit", ExitCommand]
]

cmd = commands.assoc("save")
cmd[1].new.execute if cmd

CSV-like Data

# Like a simple database
users = [
  ["alice", "Alice Anderson", "alice@example.com"],
  ["bob", "Bob Builder", "bob@example.com"],
  ["carol", "Carol Clark", "carol@example.com"]
]

users.assoc("bob")  # => ["bob", "Bob Builder", "bob@example.com"]

Method Dispatch

operations = [
  ["+", :+],
  ["-", :-],
  ["*", :*],
  ["/", :/]
]

op = operations.assoc("*")
5.send(op[1], 3)  # => 15

With Different Key Types

# Integer keys
scores = [[1, 100], [2, 95], [3, 87]]
scores.assoc(2)  # => [2, 95]

# Symbol keys
mapping = [[:red, "#f00"], [:green, "#0f0"], [:blue, "#00f"]]
mapping.assoc(:green)  # => [:green, "#0f0"]

Return Value

# Returns the entire sub-array
result = [["a", 1], ["b", 2]].assoc("a")
puts result.inspect  # => ["a", 1]

# Returns nil if not found
result = [["a", 1]].assoc("z")
puts result  # => nil

Comparison with rassoc

# assoc searches first column
table = [[1, "one"], [2, "two"], [3, "three"]]
table.assoc(2)    # => [2, "two"]

# rassoc searches second column
table.rassoc("two")  # => [2, "two"]

See Also