Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby set isn't unique

Tags:

ruby

set

For some reason the following code produce a set with duplicate values.
I'm not sure how uniqueness of an array in ruby is defined so maybe this is somehow expectable?

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 prints

#<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 x to xs + [x] will fix it.

like image 960
hsinewu Avatar asked Jun 14 '17 08:06

hsinewu


1 Answers

You are effectively altering the objects within the set, which is not allowed.

From the documentation:

Set assumes that the identity of each element does not change while it is stored. Modifying an element of a set will render the set to an unreliable state.


Regarding your comment

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

You could 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]]
like image 110
Stefan Avatar answered Oct 24 '22 06:10

Stefan