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?
One of the biggest differences between an Array and a Set is the order of elements. The documentation describes this as well: Array: “An ordered, random-access collection.” Set: “An unordered collection of unique elements.”
The Set data type was introduced in ES2015 and the difference between array and set is that while an array can have duplicate values a set can't. Elements can be accessed in array using index which isn't possible in Set since it uses keys and elements can be traversed only in the way they were entered.
In a direct comparison, Sets have several advantages over arrays, especially when it comes to a faster run-time: Search for an Item: Using indexOf() or includes() to check whether an item exists in an array is slow. Deleting an Item: In a Set, you can delete an item by its value.
In addition, Array is considered as “indexed collection” type of data structure, while Set is considered as “keyed collection”. Keyed collections are collections which use keys; these contain elements which are iterable in the order of insertion.
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[]
(e.g. Set[1,2,3]
)For me the main difference is that Set
s are implemented as hashes, so you have O(1)
membership tests for elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With