There are times, when we deal with binary data and perform bitwise operations like Left Shift, Right Shift, AND etc.
For Example:
In summary, to achieve above result we need to write expression as follows:
To simplify these kind of expressions, Ruby 2.7 has extended
Integer#[]
to support range arguments.
We can pass range (beg..end) as argument to integer i.e. selecting bits starting position from beg till end.
After Ruby 2.7
Now let’s take the above expression (n >> 2) && 0b1111
.
This is returning 4 bits starting from position 2.
Position 2 is because of 2 bits right shift
and length 4 is because of AND operation with 0b1111.
Thus with Ruby 2.7, we can write this expression like this:
This expression looks much cleaner and readable.
There is one edge case when using this. If end is less than beg in the range (beg..end) then it’ll be handled as (beg..Float::INFINITY)