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.