What is the difference between Set
and Array
in Ruby except for the fact that sets keep unique elements while arrays can keep duplicate elements?
For me the main difference is that Set
s are implemented as hashes, so you have O(1)
membership tests for elements.
They are very different.
a[3]
references the 4th object in the array.[1, 'apple', String, 1, :banana]
(this creates and initializes a new Array).Set
is not part of the core, but part of the standard library, and thus needs a require 'set'
.Set.new
.
Set[1,2,3]
)Another important difference is in the implementation of the include?
method: an Array compares members based on the result of the ==
method, while a Set uses the eql?
method.