ruby中的== eql?和equal?區別

c3tc3tc3t發表於2017-03-17

原文 http://www.wellho.net/mouth/985_Equality-in-Ruby-eql-and-equal-.html

Equality in Ruby - == eql? and equal?

 

The == comparison checks whether two values are equal

eql? checks if two values are equal and of the same type

equal? checks if two things are one and the same object.

How do I remember which is which ... The longer the operator, the more restrictive the test it performs

Example:

irb(main):013:0> val = 17
=> 17
irb(main):014:0> val == 17.0
=> true
irb(main):015:0> val.eql?(17.0)
=> false
irb(main):016:0> val.eql?(17)
=> true

 

三個等號的比較操作===
通常情況下這中方式與==是一樣的,但是在某些特定情況下,===有特殊的含義:
在Range中===用於判斷等號右邊的物件是否包含於等號左邊的Range;
正規表示式中用於判斷一個字串是否匹配模式,
Class定義===來判斷一個物件是否為類的例項,
Symbol定義===來判斷等號兩邊的符號物件是否相同。
(1..10) === 5 # true: 5屬於range 1..10
/\d+/ === "123" # true: 字串匹配這個模式
String === "s" # true: "s" 是一個字串類的例項
:s === "s" # true
irb(main):017:0> val.equal?(17)
=> true
 

相關文章