Why can procs be called with === in ruby ​​1.9?

This article mentions 4 ways to call procs in ruby ​​1.9, and === is one of them. I don’t understand why this would be done that way. Does it have anything to do with the normal value === (if two objects are the same object)?

  irb (main): 010: 0> f = -> n {[: hello, n]}
 => #
 irb (main): 011: 0> f.call (: hello)
 => [: hello,: hello]
 irb (main): 012: 0> f ===: hello
 => [: hello,: hello]
 irb (main): 013: 0> Object.new === Object.new
 => false
 irb (main): 014: 0> f === f
 => [: hello, #]
+6
source share
4 answers

This is what the docs have to say :

This means that the proc object is the target for the when clause in the case statement.

This is perhaps a contrived example:

 even = proc { |x| x % 2 == 0 } n = 3 case n when even puts "even!" else puts "odd!" end 

This works because case/when is basically done as follows:

 if even === n puts "even!" else puts "odd!" end 

case/when checks which branch is being executed by calling === in the arguments in the when clauses, choosing the first one that returns a true value.

Despite its similarity to the equality operator ( == ), it is not a stronger or weaker form. I am trying to think of === as an "belongs" operator. Class defines it so that you can check whether an object belongs to a class (i.e. it is an instance of a class or a subclass of the class), Range defines it to check if the argument belongs to a range (i.e. it is included in a range), etc. d. This doesn't really make the Proc case any clearer, but think of it as a tool for creating your own, owned by operators, as my example above; I defined an object that can determine if something belongs to a set of even numbers.

+4
source

Note that === in Ruby is NOT about equality, unlike JavaScript. It is specifically used for case expressions :

 case cats.length when 42 # Uses 42 === cats.length puts :uh when /cool/i # Uses /cool/i === cats.length puts :oh when ->(n){ n.odd? || n/3==6 } # Passes cats.length to the proc puts :my end 
+5
source

This function is useful in case of construction, when you need to calculate something when comparing.

 is_odd =-> n { n%2 != 0 } is_even =-> n { n%2 == 0 } case 5 when is_even puts "the number is even" when is_odd puts "the number is odd" end => the number is odd 
+2
source

Does === have anything to do with the normal value (asks if both objects are the same object)?

Actually, this is a common misconception about === in Ruby. This is actually not strict for comparing Object#object_id (although this is its behavior in many common calls). Ruby === uses the case of subsumption .

Here's the description === from Object : "Random equality is for the Object class, effectively the same as calling # ==, but usually redefined by descendants to provide meaningful semantics in case statements."

Unfortunately, although it consists of three = , it has nothing even remotely for equality: -D

0
source

Source: https://habr.com/ru/post/910541/


All Articles