Possible Duplicate:
=== vs. == in Ruby
Fixnum == 2.class
#=> true
Fixnum === 2.class
#=> false
why ===
doesn't work? and how can I know the method .=== belong to(right now I guess it invoke the Object#==
, or Object#===
), b开发者_开发技巧ut how can I make sure of that?
Duplicates:
- === vs. == in Ruby
- What does the "===" operator do in Ruby?
- === vs. == in Ruby
- Ruby compare objects
Case equality. See the documentation for Object#===. This method is usually overridden in subclasses of Object
. For example, Module#===:
Case Equality--Returns true if anObject is an instance of mod or one of mod’s descendants. Of limited use for modules, but can be used in case statements to classify objects by class.
>> Module.new === Module
=> false
>> Module === Module.new
=> true
Regexp#=== is another one, in which case it's a synonym of =~
:
a = "HELLO"
case a
when /^[a-z]*$/; print "Lower case\n"
when /^[A-Z]*$/; print "Upper case\n"
else; print "Mixed case\n"
end
An example in IRB:
>> "a" === /a/
=> false
>> /a/ === "a"
=> true
Remember, the first one returns false because you're doing ===
on String
which isn't the same thing. In the second example we're doing ===
on Regexp
And finally, Range is quite a good one it calls include?
on the Range object and passes your value in:
>> (1..100) === 3
=> true
>> (1..100) === 300
=> false
For a list of these, check out RubyDoc.info core documentation and search for ===
in the methods area in the left side frame
The == usually only checkes the values of both arguments, when ==== checks the types, too.
精彩评论