Why does "foo" .class === String return false?

I was curious when this did not work, as I expected:

var = "foo"
case var.class
when String
  puts "bar"
else
  puts "baz"
=> "baz"

I understand that the case statement uses ===, but I do not understand what it does ===. Documents say ...

Random equality. For the Object class, it is in fact the same as calling # ==, but it is usually overridden by descendants to provide meaningful semantics in case statements.

http://ruby-doc.org/core-2.2.3/Object.html#method-i-3D-3D-3D

Does this mean that ===in a class (or one of its modules) it overrides ===to Object? I'm confused.

+4
source share
3 answers

=== Class (, , Module ), " ".

:

>> String === ""
=> true
>> Class === String
=> true

, . , :

var = "foo"
case var
when String
  puts "bar"
else
  puts "baz"
end
# outputs "bar", since String === "foo"

: Ruby String === String, , String .

+5

case equality. . Module .

Case Equality - true, . , case .

=== Ruby is_a?.

false, "Foo".class string.

"Foo".class.is_a?(String)
=> false
+2

This is due to the way the case equivalence operator is used for classes ===. Use an object, not object.class

var = "foo"
case var
when String
  puts "bar"
else
  puts "baz"
=> "bar"
+1
source

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


All Articles