1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

equal? / eql? / == の違い

Posted at

equal?(オブジェクトの同一性)

・同じオブジェクトかどうか(object_id が一致するか)を判定
・値が同じでもオブジェクトが違えば false

str1 = "ruby"
str2 = "ruby"

p str1.equal?(str2)  # => false (別オブジェクト)
p :ruby.equal?(:ruby) # => true (シンボルは唯一のオブジェクト)
p 1.equal?(1)         # => true (整数は即値なので同一)

eql?(値の等価性 + 型も見る)

・値が同じかつ型も同じ なら true
・ハッシュのキー比較などに使われる

p 1.eql?(1)     # => true
p 1.eql?(1.0)   # => false (整数と小数は型が違う)
p "a".eql?("a") # => true

==(値の等価性)

・値が同じなら true(型はあまり気にしない)
・多くのクラスでオーバーライドされている

p 1 == 1.0    # => true
p "ruby" == "ruby"  # => true

まとめ

メソッド 判定内容
equal? 同一オブジェクトか "a".equal?("a".dup) → false
eql? 値 + 型が同じか 1.eql?(1.0) → false
== 値が同じか 1 == 1.0 → true

ポイント
・equal? は object_idベース
・eql? は ハッシュキー用
・== は 一般的な値の比較

rubysilverで出てきたこれを使った問題の解説です!

arr = [
  true.equal?(true),         # true
  nil.eql?(NilClass),        # false
  String.new.equal?(String.new), # false
  1.equal?(1)                # true
]

p arr.collect { |a| a ? 1 : 2 }.inject(:+)
# => 6

おまけ
collect { |a| a ? 1 : 2 } の解説

collect は map と同じで、配列の各要素にブロックを適用して新しい配列を作ります。
この { |a| a ? 1 : 2 } は 三項演算子らしいです!

条件式 ? 真のときの値 : 偽のときの値

つまり a が true なら 1、false なら 2 に変換するってこと。

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?