We often ruby code or rails framwork, usually the ===
operator is quite seldom used if you have js code then will use more than it is a trict mode
tring JS. Today they will try to see if it can really do anything in ruby or it is different from what JS
What is Triple Equal?
In the default cases, 3 equal signs ===
it will be alias of ==
. But in some special cases other classes overide its behavior. Let’s go to the specific case:
Ranges
1 2 | (1..10) === 1 # true |
Trong một range (dải) thì '===' là alias của 'includes?'
Regex
1 2 | /abc/ === 'abcdef' # true |
With regex, it is a match
.
Classes
1 2 | String === 'foo' |
For a class, is it equivalent to is_a?
Procs
1 2 | `-> a { a > 5 } === 6` |
With a proc, we call
. This will be interesting later.
Just in Case
Now that we have a few cases, we’ll use the case
in Ruby:
1 2 3 4 5 6 | case '10.0.0.1' when IPAddr.new('10.0.0.0/8') then 'wired connection' when IPAddr.new('192.168.1.0/8') then 'wireless connection' else 'unknown connection' end |
Not very interesting either
Querying
Most of us have used ActiveRecord before, similar to the way we query below:
1 2 | Person.where(name: 'Bob', age: 10..20) |
It looks like the above command is still running but how is it true that ===
is used in this: We come up with an example that assumes we have 1 of the following hashes:
1 2 3 4 5 6 7 8 | people = [ {name: 'Bob', age: 20}, {name: 'Sue', age: 30}, {name: 'Jack', age: 10}, {name: 'Jill', age: 4}, {name: 'Jane', age: 5} ] |
Normally if in ruby to be able to remove but people over 20 years old we will do the following:
1 2 | people.select { |person| person[:age] >= 20 } |
And this is how ActiveRecord we overide work with where
1 2 3 4 5 6 7 | def where(list, conditions = {}) return list if conditions.empty? list.select { |item| conditions.all? { |key, matcher| matcher === item[key] } } end |
JSON Packet Dump
Assuming we have finished with JSON, we can query it:
1 2 3 4 5 6 | where(packets, source_ip: IPAddr.new('10.0.0.0/8'), dest_ip: IPAddr.new('192.168.0.0/16') ttl: -> v { v > 30 } ) |
Note that JSON will give you String keys unless you say otherwise about parsing, so be careful there.
Objects
OK, now we use the overide where
input statement is the list object. Instead of using item[key]
we use item.public_send(key)
:
1 2 3 4 5 6 7 8 9 | def where(list, conditions = {}) return list if conditions.empty? list.select { |item| conditions.all? { |key, matcher| matcher === item.public_send(key) } } end |
It is special not to go to a more advanced example:
1 2 3 4 5 6 7 8 9 | def where(list, conditions = {}) return list if conditions.empty? list.select { |item| conditions.all? { |key, matcher| matcher === item.public_send(*key) } } end |
Finishing Up
Above are some examples of the ===
operator applied in ruby or how we use it to customize ActiveRecord commands.
Reference
https://medium.com/rubyinside/triple-equals-black-magic-d934936a6379