Ruby: Intersection/Difference/Concatenation with collections
We came across a couple of situations yesterday where we wanted to perform operations on two different arrays.
My immediate thought was that there should be some methods available similar to what we have in C# which Mike Wagg and I spoke about in our talk about using functional programming techniques in C#.
I was expecting to find methods with names indicating the operation they perform but in actual fact the methods are more like operators which makes for code that reads really well.
Intersection
This is useful when we have two collections and want to find the elements that exist in both of them.
In the world of C# we have an 'Intersect' method available as part of the LINQ library:
var collection1 = new int[] { 1,2,3,4 };
var collection2 = new int[] { 1,2,5,6 };
collection1.Intersect(collection2);
In Ruby we have the '&' method:
ruby-1.8.7-p299 > [1,2,3,4] & [1,2,5,6]
=> [1, 2]
Difference
This is useful when we have two collections and want to find items which are in one collection and not in the other.
In C# we can use the 'Except' method…
var collection1 = new int[] { 1,2,3,4 };
var collection2 = new int[] { 1,2 };
collection1.Except(collection2);
…whereas in Ruby we have the '-' method:
ruby-1.8.7-p299 > [1,2,3,4] - [1,2]
=> [3, 4]
Concatenation
This is useful when we have two collections and want to join the two collections together.
In C# we’d use the 'Union' method..
var collection1 = new int[] { 1,2,3 };
var collection2 = new int[] { 4,5,6 };
collection1.Union(collection2);
ruby-1.8.7-p299 > [1,2,3] + [4,5,6]
=> [1, 2, 3, 4, 5, 6]
These methods and others on array are well documented on ruby-doc.org
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.