Something special about the Triple Equal operator in ruby

Tram Ho

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

Trong một range (dải) thì '===' là alias của 'includes?'

Regex

With regex, it is a match .

Classes

For a class, is it equivalent to is_a?

Procs

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:

Not very interesting either ?

Querying

Most of us have used ActiveRecord before, similar to the way we query below:

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:

Normally if in ruby ​​to be able to remove but people over 20 years old we will do the following:

And this is how ActiveRecord we overide work with where

JSON Packet Dump

Assuming we have finished with JSON, we can query it:

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) :

It is special not to go to a more advanced example:

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

Share the news now

Source : Viblo