Skip to content

Instantly share code, notes, and snippets.

@pmarreck
Created February 19, 2013 16:59
Show Gist options
  • Save pmarreck/4987732 to your computer and use it in GitHub Desktop.
Save pmarreck/4987732 to your computer and use it in GitHub Desktop.
Detect a recursive data structure in Ruby
module Enumerable
def recursive?(oids = {})
if oids.key?(self.object_id)
return true
else
oids[self.object_id] = 1
return any?{ |v| v.recursive?(oids) if v.respond_to?(:recursive?) }
end
return false
end
end
p [1,2,3,{a: 'b'}].recursive?
h = {}
h[0] = h
p h
p h.recursive?
a = []
a << a
p a
p a.recursive?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment