1 min read

TIL: Ruby Associative Arrays

Using arrays as if they had keys

Sometimes you have to look up items in an array as if they have keys.

food = [
  ['British', 'Roast Beef'],
  ['French', 'Coq au Vin'],
  ['Spanish', 'Paella']
]

food.assoc('British')
# ["British", "Roast Beef"] 

And I can go the other way:

food.rassoc('Coq au Vin')
# ["French", "Coq au Vin"]

What happens if I have keys with multiple values?

food = [
  ['British', 'Roast Beef'],
  ['British', 'Spotted Dick'],
  ['French', 'Coq au Vin'],
  ['Spanish', 'Paella']
]

food.assoc('British')
# ["British", "Roast Beef"] 

You only get the first value back.

What happens if you have a sub-array with more than two elements?

food = [
  ['British', 'Roast Beef', 'Red Meat'],
  ['French', 'Coq au Vin', 'Chicken'],
  ['Spanish', 'Paella', 'Seafood']
]

food.assoc('British')
# ["British", "Roast Beef", "Red Meat"] 

food.rassoc('Paella')
# ["Spanish", "Paella", "Seafood"] 

food.rassoc('Seafood')
# nil

assoc and rassoc only work on the first and second items in the array, but the other elements of the array are returned on a match.