Created
February 19, 2013 16:59
-
-
Save pmarreck/4987732 to your computer and use it in GitHub Desktop.
Detect a recursive data structure in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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