Skip to content

Instantly share code, notes, and snippets.

@christopherfujino
Last active August 17, 2017 15:34
Show Gist options
  • Save christopherfujino/f31354d485f9db7c8d966a9350f2695e to your computer and use it in GitHub Desktop.
Save christopherfujino/f31354d485f9db7c8d966a9350f2695e to your computer and use it in GitHub Desktop.
How to use Ruby's array.assoc method.

array.assoc(obj) => array or nil

The assoc method for Ruby arrays takes a single argument and searches for the matching element that is an array whose first element matches the argument. It then returns either the matching sub-array or nil if none was found.

This is a fairly common task in situations where a hash is used to collect a set of data and the keys are used as unique identifiers. I chose this method because I am tired of writing some form of the same basic function in JavaScript:

let beardLengths = [
  {name: 'cory', length: 5},
  {name: 'justin', length: 4}
];

function findByName(arr, name) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].name === name) return arr[i];
  }
  return null;
}

findById(beardLengths, 'cory'); // => {name: 'cory', length: 5}

This doesn't take long to write, but it does involve setting up a loop. Even worse, it feels like I'm inventing the wheel. Here's the Ruby implementation, using .assoc:

beard_lengths = [
  ['cory', 5],
  ['justin', 4]
]

beard_lengths.assoc('cory') # => ['cory', 5]

This is much more brief, however has the drawback of necessitating nested arrays with subarrays having a known ordering of elements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment