This post is going back to the basics. When I used to program in C and C++, it was common to see code using bitwise operators. These operations are a great method for storing information concisely and efficiently. (Wikipedia has a helpful overview, if you're interested.)
With the abundance of memory and disk space today, conciseness and efficiency aren't always at the top of a developer's concerns. I haven't seen or used many bitwise operations lately. That is, of course, until I needed a simple and clean solution
to a problem.
This post will cover the basics of `&` and `|` bitwise operators.
That code gets the job done. However, a much more concise way of accomplishing this task would be to use the `&` operator.
a & b # => [3, 4]
Now instead of the intersection, say you were asked for the union of the two arrays. This could be achieved with the following code.
(a + b).uniq # => [1, 2, 3, 4, 5, 6]
Or, you could employ a bitwise operator.
a | b # => [1, 2, 3, 4, 5, 6]
As you can see, bitwise operators can help you solve basic problems concisely. Interestingly, these examples of operations on arrays are not necessarily more efficient. In my next post, I'll dig deeper into this subject.