【问题标题】:How find a nth node value using ruby如何使用 ruby​​ 找到第 n 个节点值
【发布时间】:2016-07-13 13:07:20
【问题描述】:

我有一个类似结构的 JSON 响应树

{
  "id":""
  "node": [
      {
        "id":""
        "node": [
              {
                "id":""
                "node":[] 
           }
        ]
     }
  ]
}

我怎样才能得到最后一个 id 值,这只是一个例子,它可能包含 n 个循环。

【问题讨论】:

    标签: ruby json api parsing


    【解决方案1】:
    h = {
      "id" => "1",
      "node" => [
        {
          "id" => "2",
          "node" => [
            {
              "id" => "3",
              "node" => []
            }
          ]
        }
      ]
    }
    
    
    ▶ λ = ->(h) { h['node'].empty? ? h['id'] : λ.(h['node'].last) }
    #⇒ #<Proc:0x00000002f4b490@(pry):130 (lambda)>
    ▶ λ.(h)
    #⇒ "3"
    

    【讨论】:

    • 我知道这无关紧要,但我该如何输入λ
    • @Aetherus 我在 Linux 上使用非常自定义的键盘布局,通过 xkb 在/usr/share/X11/xkb/symbols 中的布局进行操作。 MacOS/Windows ⚑ 作为操作系统很烂。
    • @lurker 是的,让我们生活在 XX 世纪,输入 10 个字符,而不是一个最适合这里且最容易阅读的字符。
    • @mudasobwa 我会在我的 Elementary OS 上试一试,我完全同意 Windows 很糟糕。至于MacOS,我不知道,因为我用的不多。
    • @Aetherus google 用于“xkb 自定义布局”等;不要忘记include "level3(ralt_switch)",您将免费获得约 80 个您选择的额外符号:)
    【解决方案2】:

    也许这个方法会对你有所帮助。您可以使用子哈希调用递归方法。

    h = {
      "id" => "1",
      "node" => [
        {
          "id" => "2",
          "node" => [
            {
              "id" => "3",
              "node" => []
            }
          ]
        }
      ]
    }
    
    def get_last_node(h)
      if Array === h['node'] && !h['node'].empty?
        h['node'].each do |node_h|
          id = send(__callee__, node_h)
          return id if id
        end
        nil
      else
        h['id']
      end
    end
    
    get_last_node(h)
    # => 3
    

    【讨论】:

    • 考虑使用__callee__而不是__method__,因为前者返回别名的别名,而后者返回实际方法名,即使通过别名调用也是如此。
    【解决方案3】:

    类似于@mudasobwa 的回答:

    def get_last_node(h)
      h["node"].empty? ? h["id"] : get_last_node(h["node"].first)
    end
    
    get_last_node(h)
      #=> 3
    

    【讨论】:

      猜你喜欢
      • 2017-02-19
      • 1970-01-01
      • 2011-01-25
      • 2022-10-06
      • 1970-01-01
      • 2011-01-21
      • 2012-12-06
      • 1970-01-01
      • 2020-04-17
      相关资源
      最近更新 更多