0
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?

set の概要、配列との違い

Posted at

配列Arrayと似ていると言われる集合setだが何が配列と違うのか。

配列には順番がある
setには順番は保証されない

配列は重複を許す
setは重複を許さない
数学の集合を思い出すと理解しやすい

どんな時にsetを使えばいいのか

演算を高速に行いたい場合。

配列はハッシュのような仕組みを使っているためsetより低速

集合演算を行いたい場合

両方の集合に共通している人を抜き出す
片方の集合には属しているがもう片方の集団には属していない人を抜き出す。

setの配列と同じ使い方

.add
.delete
.size
.emply?
.include?
等が配列と同じく使える

setの配列とは違う使い方 実践 

定義の仕方

require 'set'
a = Set[]

重複は許可されない

set = Set[]
set.add("kome")
set.add("pan")
set.add("pan") 

p a   #=> #<Set: {"pan","kome"}> 

和集合( rubyの||と間違いえないように注意)

set_a = Set[1, 2, 3]
set_b = Set[3, 4, 5]
p (set_a | set_b)  #=> #<Set: {1, 2, 3, 4, 5}>

積集合(rubyの&&と間違いえないように注意)

set_a = Set[1, 2, 3]
set_b = Set[3, 4, 5]
p (set_a & set_b)  #=> #<Set: {3}>

その他 差集合等、集合に関する演算を使用できる。

0
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
0
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?