加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将带括号的字符串转换为树,Ruby

发布时间:2020-12-17 02:23:32 所属栏目:百科 来源:网络整理
导读:我有一个字符串“动物(爬行动物鸟(老鹰鸽子乌鸦))”,我需要返回: a = [ { "Animals" = [ { "Reptiles" = nil },{ "Birds" = [ { "Eagles" = nil },{ "Pigeons" = nil },{ "Crows" = nil } ] } ] }] 我不明白我是怎么做到的. 在哪里我可以找到一些例子或我可
我有一个字符串“动物(爬行动物鸟(老鹰鸽子乌鸦))”,我需要返回:

a = [
  {
    "Animals" => [
      {
        "Reptiles" => nil
      },{
        "Birds" => [
          { "Eagles" => nil },{ "Pigeons" => nil },{ "Crows" => nil }
        ]
      }
    ]
  }
]

我不明白我是怎么做到的.
在哪里我可以找到一些例子或我可以在谷歌搜索?

解决方法

这是一种可以将字符串转换为数组的方法.

def arrayify(arr)
  a = split_arr(arr)
  a.map do |h|
    k = h.keys.first
    v = h.values.first
    case v
    when Array then { k => arrayify(v) }
    else { k=>v }
    end
  end
end

def split_arr(arr)
  a = []
  while arr.any?
    word = arr.shift
    if arr.empty? || arr.first != ?(
      a << { word=>nil }
    else
      arr.shift
      close_count = 0
      b = []
      loop do
        token = arr.shift
        case token
        when ?)
          break if close_count == 0
          close_count -= 1
        when ?( then close_count += 1
        end
        b << token
      end
      a << { word=>b }
    end
  end
  a
end

str = "Animals ( Reptiles Birds ( Eagles Pigeons Crows ) ) Foods ( " +
      "Snacks Breakfast ( Pancakes Waffles ) )"

arrayify(str.split)

  #=> [{"Animals"=>[{"Reptiles" =>nil},#                 {"Birds"    =>[{"Eagles" =>nil},#                                {"Pigeons"=>nil},#                                {"Crows"  =>nil}
  #                               ]
  #                 }
  #                ]
  #    },#    {"Foods"  =>[{"Snacks"   =>nil},#                 {"Breakfast"=>[{"Pancakes"=>nil},#                                {"Waffles" =>nil}
  #                               ]
  #                 }
  #                ]
  #    }
  #   ]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读