LoginSignup
4
4

More than 5 years have passed since last update.

差集合を取りたいとき…

Posted at

2つの配列の差を取りたいとき,Array#- という名前的にもどんぴしゃなメソッドがあるわけですが,

self - other -> Array[permalink][rdoc]
自身から other の要素を取り除いた配列を生成して返します。
要素の同一性は Object#eql? により評価されます。 self 中で重複していて、other中に存在していなかった要素は、その重複が保持されます。

と書いてあります ( http://docs.ruby-lang.org/ja/2.2.0/class/Array.html ).

つまり,以下の結果は空の配列ではありません.

class C
  def ==(other)
    true
  end
end

[C.new, C.new, C.new] - [C.new, C.new, C.new]  #=> [#<C:0x007fc6dc98d370>, #<C:0x007fc6dc98d348>, #<C:0x007fc6dc98d320>]

== で比較してくれるものだと思い込んでいたので,あれ?ってなりました.== を使いたければ,

a = [C.new, C.new, C.new]
b = [C.new, C.new, C.new]
a.reject{|e| b.include? b}

とかですかね.

Array#include

include?(val) -> bool[permalink][rdoc]
配列が val と == で等しい要素を持つ時に真を返します。

なので ( http://docs.ruby-lang.org/ja/2.2.0/class/Array.html ),上の結果は [] になります.

ということを今更ながら知りました.めでたし.

4
4
0

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
4
4