I've never used bit operation in my life.
But currently, I've got a chance to know how it is good.
I will develop this post, but publish it first anyway.
case.1 For day matching operation
Define and WHY
You can define days like this.
MON = 1
TUE = 2
WED = 4
THU = 8
...
Maybe, you've got a question, WHY?
Let's see it in bit world.
MON.to_s(2).to_i #=> 1
TUE.to_s(2).to_i #=> 10
WED.to_s(2).to_i #=> 100
THU.to_s(2).to_i #=> 1000
...
PROS
If a user check MON and WED, it's easy to calculate now.
MON | WED #=> 5 ( MON = 1, WED = 4 )
The bit of 5 is 101
which made of 001
and 100
.
It's easy π
Use it with Date
Date.today #=> Thu, 30 Jan 2020
Date.today.wday #=> 4
MON = 1 # = 2**0
TUE = 2 # = 2**1
WED = 4 # = 2**2
THU = 8 # = 2**3
...
So, you can get the bit of the date from Date object.
2**(Date.today.wday - 1) #=> 8
Take the multi case of the date by the 1 operation
You can filter the cases include "WED" by bitwise &.
Image is like this.
0000 #0 NAN
0001 #1 MON
0010 #2 TUE
0011 #3 TUE and MON
0100 #4 WED
0101 #5 WED and MON
0110 #6 WED and TUE
0111 #7 WED and TUE and MON
&&&&
0100 # WED
Example: 3 & 4 #=> 0
( TUE and MON & WED )
Because,
0011 # TUE and MON
&&&&
0100 # WED
----
0000
Example: 5 & 4 #=> 4
( WED and MON & WED )
Because,
0101 # TUE and MON
&&&&
0100 # WED
----
0100 #=> 4
0 & 4 #=> 0
1 & 4 #=> 0
2 & 4 #=> 0
3 & 4 #=> 0
4 & 4 #=> 4
5 & 4 #=> 4
6 & 4 #=> 4
7 & 4 #=> 4
So, we can check it is valid of not by '=='
3 & 4 == 4 #=> 0 == 4 #=> false
5 & 4 == 4 #=> 4 == 4 #=> true
By this mechanism, you can easily make sure the date matches the day?
Use it in SQL, Relation, ActiveRecord, WHERE
Now, you can understand it. ( SQL also has the bitwise & operator. )
.where("user_selected_days & ? = ?", 2**(Date.today.wday - 1), 2**(Date.today.wday - 1))
Top comments (0)