Ruby is_a? vs ===

What is the difference between is_a?and ===?

Running this code:

puts myObj.class
puts myObj.is_a?(Hash)
puts myObj === Hash   #Curious 
puts Hash  === myObj

Output:

Hash
true
false        #Why?
true
+4
source share
3 answers

Ruby, String, Range Regexp, ===, case-equal, triple equals threequals. - , - , . , true, "" " " . , , ( ).

String === "zen"  # Output: => true
Range === (1..2)   # Output: => true
Array === [1,2,3]   # Output: => true
Integer === 2   # Output: => true

, , , . , , , .

2.is_a? Integer   # Output: => true
2.kind_of? Integer  # Output: => true
2.instance_of? Integer # Output: => false

, false, , 2, Fixnum, Integer. ===, is_a? instance_of? true, . instance_of true, , .

is_a? kind_of? Kernel, Object. . :

Kernel.instance_method (: kind_of?) == Kernel.instance_method (: is_a?) # : = > true

ruby.

+5

, === .

=== -, , . Object#is_a? (. ).

, , .

+2

Clear example

1)$> Integer === 1 # => true 

2)$> 1 === Integer # => false

1) 1 is an instance of Integer, but 2) Integer is not an instance of 1.

But also returns true if it is an instance of any of its subclasses , for example:

$ > Numeric === 1   # => true 
$ > Numeric === 1.5 # => true

$ > Fixnum === 1    # => true 
$ > Fixnum === 1.5  # => false
+1
source

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


All Articles