Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Working with Nested Sets

You should be aware that Set does not guarantee that nested sets stored in it are unique. This is because foo_set.eql? bar_set will never return true - even if the sets have exactly the same values in them. Other kinds of objects in Ruby exhibit this behavior, so keep your eyes open.

If you would like to iterate over the contents of sets without having to worry about the nested data possibly colliding with the upper data, you cannot use Set#flatten. Here is a simple method to recursively walk through such a set:

class Set
    def each_recur(&block)
        each do |elem|
            if elem.is_a? Set

my_set = Set.new.add([1, 2, 3, 4].to_set).add([1, 2,
3, 4].to_set)
    #=> #<Set: {#<Set: {1, 2, 3, 4}>, #<Set: {1, 2,
3, 4}>}>

my_set.each_recur { |elem| print(elem, " ") }


1 2 3 4 1 2 3 4
  • + Share This
  • 🔖 Save To Your Account