What is Triple equals?
By default it is the alias of the == comparison operator with the use of equal comparison of values and data types. It is most evident when classes override their own behavior. Let’s see some examples of it:
Ranges
1 2 3 4 5 6 | (1..10) === 1 # => true (1..10).include?(1) # => true |
For Ranges, === is an alias for includes? , it helps you check if the value is in a given ranges. More specifically, it doesn’t just check numbers, with a range of String that is still checkable.
1 2 3 4 | SUPPORTS_PATTERN_MATCH_VERSIONS = '2.7.0'..'3.0.0' SUPPORTS_PATTERN_MATCH_VERSIONS === '2.7.5' # => true |
Regular Expressions
1 2 3 4 5 6 | /abc/ === 'abcdef' # => true /abc/.match?('abcdef') # => true |
As for Regex, === is a secret for the match? , for a given Regex it checks to see if the string to be compared is a child of the Regex result set.
Classes
1 2 3 4 5 6 | String === 'foo' # => true 'foo'.is_a?(String) # => true |
For Class, === is a secret for is_a? , check if the given value belongs to this class or not?
Functions (Proc and Lambda)
Ruby has several ways to represent anonymous functions, procs, and lambdas. They can be expressed as follows:
1 2 3 | add_one_lambda = -> x { x + 1 } add_one_proc = proc { |x| x + 1 } |
1 2 3 4 5 6 7 8 9 10 11 | add_one_lambda = -> x { x + 1 } add_one_lambda === 1 (object) # => 2 add_one_lambda.call(1) # => 2 add_one_lambda.(1) # => 2 add_one_lambda[1] # => 2 |
Here === is similar to the call method. Proc and Lambda s will be called with params as object to be executed. The block will be run and return results corresponding to the value you passed.
IP Addresses
Ruby also has features for all of us operations and network types, IPAddr:
1 2 3 4 | require 'ipaddr' IPAddr.new('10.0.0.1') |
You can instantiate subnets using it:
1 2 3 4 | local_network = IPAddr.new('192.168.1.0/24') local_network.include?('192.168.1.1') # => true |
Use === instead of include? as here:
1 2 3 | local_network === '192.168.1.1' # => true |
Here we are checking if the IP address is a member of a certain subnet or not
Conclude
There are many interesting things about the === comparison operator, here I only introduce a few, you can learn more at the link below.
https://medium.com/rubyinside/triple-equals-black-magic-d934936a6379
https://dev.to/baweaver/understanding-ruby-triple-equals-2p9c