Leon's Blogging

Coding blogging for hackers.

Ruby - == vs === vs Eql? Vs Equal?

| Comments

  • ==: 比較兩邊的 value
  • eql?: 比較兩邊的 value + class type
  • equal?: 比較兩邊的 object_id
  • ===: case equality ,比較像是 A 描述了一個集合,B 屬於 A 嗎?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
a, b = 1, 1
a == b     # => true
a === b    # => true
a.eql? b   # => true
a.equal? b # => true

a, b = 1, 1.0
a == b     # => true
a === b    # => true
a.eql? b   # => false
a.equal? b # => false

a, b = 1, "1"
a == b     # => false
a === b    # => false
a.eql? b   # => false
a.equal? b # => false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Class  === Class  # => true
Object === Object # => true
Class  === Object # => true
Object === Class  # => true

# 就 Ruby Gotchas 解釋比較像是 Fixnum 有包含 1,1 卻不包含 Fixnum
1 === 1            # => true
Fixnum === 1       # => true
1 === Fixnum       # => false
Fixnum === Fixnum  # => false

(1..5) === 3           # => true
(1..5) === 6           # => false

Integer === 42          # => true
Integer === 'fourtytwo' # => false

/ell/ === 'Hello'     # => true
/ell/ === 'Foobar'    # => false

[1, 2, 3] === [1, 2, 3]
# => true
[1, 2, 3] === [1, 2]
# => false

參考文件

Comments