Ruby set is not unique

For some reason, the following code creates a collection with duplicate values.
I'm not sure how ruby ​​uniqueness of an array is defined, so maybe this is somehow expected?

require 'set'
xs = [1, 2, 3]
xss = Set.new []
xs.each do |x|
  xss.merge xss.to_a.map{|xs| xs.push x}
  xss.add [x]
  p xss
end

will print

#<Set: {[1]}>
#<Set: {[1, 2], [1, 2], [2]}>
#<Set: {[1, 2, 3, 3], [1, 2, 3, 3], [2, 3], [1, 2, 3, 3], [2, 3], [3]}>

What's wrong?

EDIT
change xs.push xuntil xs + [x]will be fixed.

+6
source share
1 answer

You effectively modify objects within a set, which is not allowed.

In the documentation:

Set assumes that the identifier of each element does not change during its storage. Changing a set item will cause the set to be unreliable.


Regarding your comment

I want #<Set: {[1], [1, 2], [2], [1, 3], [1, 2, 3], [2, 3], [3]}>

You can use Array#combination:

a = [1, 2, 3]

(1..a.size).flat_map { |n| a.combination(n).to_a }
#=> [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
+7
source

All Articles