如何检测包含下面的a,b和c等递归结构的数组或散列?
@H_301_15@解决方法
>最简单的递归数组实例
a = [] a[0] = a a # => [[...]]
>递归周期/深度不是一个
b = [[],:foo] b[0][0] = b b # => [[[...]],:foo]
>非根级别的递归
c = [a,:foo] c # => [[...],:foo]
我喜欢递归.
这是一个不错的方式,迭代所有内容并保持您看到的对象的哈希值(用于快速查找)
class Object def is_recursive?(known = {}) false end end module Enumerable def is_recursive?(known = {}) return true if known.include?(self) known[self] = true begin any? do |*args| args.any?{|item| item.is_recursive?(known)} end ensure known[self] = false end end end x = []; x << x p x.is_recursive? # => true p ({x => 42}).is_recursive? # => true p [{foo: x}].is_recursive? # => true p [[[[[[:foo],{bar: [42]}]]]]].is_recursive? # => false
请注意,这有点粗糙,你可能遇到麻烦.例如,你有[1..Float :: INFINITY] .is_recursive?的无限循环,虽然这很容易用
class Range def is_recursive?(known = {}) false # optimization end end