ruby - 如何检测递归数组和哈希?

标签 ruby arrays recursion hash

如何检测包含递归结构的数组或散列,例如下面的 abc

  • 递归数组的最简单实例

    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

关于ruby - 如何检测递归数组和哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23002354/

相关文章:

ruby-on-rails - 单表继承事件管理模型映射问题 rails 4

javascript - 将Javascript数组解析为PHP问题

sql - 具有递归 CTE : sorting/ordering children by popularity while retaining tree structure (parents always above children) 的 Postgres

c - 跟踪递归函数

ruby - 如何 Jar 和 Zip 项目?

mysql - 在具有不同字段的数据库中进行 Rails 搜索

ruby-on-rails - 如果在 excel 中更改了该行的任何单元格,如何在该行中添加标识符?

C - 从函数返回数组

c++ - 如何将数组对象(Class Template c++)作为参数传递给函数?

bash - 奇怪的 bash 别名扩展