LoginSignup
9
3

More than 5 years have passed since last update.

配列 a の全ての要素が配列 b に含まれることを確認する

Last updated at Posted at 2018-08-29

方法

:sob: 愚直な方法

a = [1, 2]
b = [3, 2, 1]
a.all? { |a_el| b.include?(a_el) } #=> true

c = [1, 4]
c.all? { |c_el| b.include?(c_el) } #=> false

:neutral_face: まずまずの方法

配列を集合とみなし、a と b の積集合が a と一致すれば、a は b の部分集合だとみなす。ただし、a に重複する要素がないことが前提。

a = [1, 2]
b = [3, 2, 1]
a & b == a #=> true

c = [1, 4]
c & b == c #=> false

シンプルだが直感的ではない。

:smiley: よい方法

Set を使えば集合専用のメソッドが使える。

a = [1, 2]
b = [3, 2, 1]
a.to_set.subset?(b.to_set) #=> true

c = [1, 4]
c.to_set.subset?(b.to_set)

シンプルさは前の方法に劣るが、Set#subset? のおかげで可読性が上がる。

9
3
4

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
9
3