如何处理这样的递归父/子问题? [英] How to handle recursive parent/child problems like this?

查看:50
本文介绍了如何处理这样的递归父/子问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在网络开发中,我经常遇到这些问题.

例如,我们有一个庞大的 URL 列表,采用这种格式:

<前>/企业/企业/食品/企业/食品/温蒂斯/企业/食品/温蒂斯/辣椒/企业/食品/温蒂斯/薯条/企业/食品/温蒂斯/鸡块/企业/药房/简历/企业/药房/cvs/牙膏/企业/药房/cvs/牙膏/品牌...

然后我们需要输出每一个,其中父类别在 h1 标签中,子类别在 h2 标签中,其子类别在 h3 标签中.

我可以处理这个问题,但我觉得我的代码很乱.我确定有我可以使用的设计模式吗?Langs 通常是 ruby​​/php.你会怎么处理?

解决方案

这个有点压缩,但我希望它有意义.当然,您可以对其进行基准测试以对其进行调整以获得最优化的结果.

s.each { |row|puts row[1..-1].split('/')[0..2].each_with_index \{|v,i|tag = "h#{i+1}";打印<#{tag}>#{v}</#{tag}>"}}

更详细

s.each do |row|# 'each' 将分割每一行row = row[1..-1] # 没有'/'的行的字符串words = row.split('/') # 拆分成单词words = words[0..2] # 我们只需要前 3 个标签words.each_with_index 做 |词,索引|# 获取单词数组中每个元素的索引和值tag = "h#{index+1}" # 使用索引动态生成标签print "<#{tag}>#{word}</#{tag}> " # 使用标签和单词生成输出结尾结尾

您应该

  1. 将方法放在适当位置的库中
  2. 收集数组中的值
  3. 在视图中遍历数组并生成标签

In web dev I come across these problems a lot.

For example, we have a giant list of URLs that are in this format:

/businesses  
/businesses/food  
/businesses/food/wendys  
/businesses/food/wendys/chili  
/businesses/food/wendys/fries  
/businesses/food/wendys/chicken-nuggets  
/businesses/pharmacy/cvs  
/businesses/pharmacy/cvs/toothpaste  
/businesses/pharmacy/cvs/toothpaste/brand  
...

and then we need to output each one, where the parent category is in h1 tags, the child is in h2 tags, and the children of that are in h3 tags.

I can handle this but I feel my code is messy. I'm sure there is a design pattern I can use? Langs are ruby/php usually. how would you handle this?

解决方案

This one is a little compressed, but I hope it makes sense. Of course you can benchmark it to tune it for most optimized result.

s.each { |row|
  puts row[1..-1].split('/')[0..2].each_with_index \
  {|v,i| 
    tag = "h#{i+1}";
    print "<#{tag}>#{v}</#{tag}> "
  }
}

more detailed

s.each do |row|                             # 'each' will split each row
  row = row[1..-1]                          # string of the row without '/'
  words = row.split('/')                    # split into words
  words = words[0..2]                       # we just need first 3 tags
  words.each_with_index do |word, index|    # get index and value of each element in word array
    tag = "h#{index+1}"                       # use index to dynamically generate tag
    print "<#{tag}>#{word}</#{tag}> "       # use the tag and word to generate output
  end
end

You should

  1. put the method in a library of appropriate place
  2. collect the values in an array
  3. loop through the array in the view and generate tags

这篇关于如何处理这样的递归父/子问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆