I am trying to merge two arrays of objects in ruby. The objects have two relevant fields; id and reach_cost.
I want my resultant array to contain unique ids, where each object has the smallest reach_cost in the case of a collision.
Running;
result = a1 | a2;
Yields mixed results, it appears that elements of a1 take precedence over elements of a2.
I could of course iterate over both arrays and make the comparison on element.reach_cost manually, but this is a high performance environment, and this method gets called an awful lot. For that reason I am trying to leverage the native components of the | operator.
Is it possible to direct the | operator to prefer one object over another? Perhaps by overriding <=> or similar?
I have read the source code of the | operator in the docs but it doesn’t appear to make any comparison, merely preferring the first array parameter over the second.
I suggest storing these arrays as hashes. This provides O(1) id lookup. Here’s what the code may look like:
This should work pretty fast.
If you like one-liners, here’s one (kindly provided by @steenslag in the comments):