开发者

Ruby comparison operators? == vs. === [duplicate]

This question already has answers here: 开发者_运维知识库 What's the difference between equal?, eql?, ===, and ==? (8 answers) Closed 8 years ago.

What's the difference between == and ===? Which one should you use when?


Both are just methods called on objects. This means that the objects decide which means what. However, there are conventions in Ruby about how these are different. Usually, == is stricter than === - a === b will almost always be true if a == b is. The best place to read about this is http://ruby-doc.org/core/classes/Object.html. Scroll down to the different sections about == and ===. Here are some of the conventions I know about:

  • ==, when applied to plain Objects, will only be true if one is exactly the same as the other - if they are stored in the same memory location (this is how Ruby works internally). If the arguments are of types other than Object, though, this method will usually be overridden.
  • equal? is just like == for plain Objects, but will never be overridden by subclasses.
  • === is used for:
    • an is_a? alternative, backwards. String === 'str' is true.
    • matching regexes. /s[at]r*/ === 'str' is true.

You can find the specific meaning of === for various classes in the documentation for those classes, for example, the Range version is here (a synonym for include?): http://ruby-doc.org/core/classes/Range.html#M000691


== is used for equality in conditional statements like if, unless, etc. === is used for determining equality in case statements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜