在Ruby中写一个headerHTML标签降价解析器

Write a header HTML tag markdown parser in Ruby

以下是我能想到的最好的;

def markdownparser(markdown)  
  if markdown.match("#")
    arr = markdown.split("")
    i = 0
    while arr[i] != " "
      if arr[i] == "#"
        i += 1
      end 
    end
    final = markdown[(i + 1)..(markdown.size + i)]
    return "<h" + i.to_s + ">" + final + "</h" + i.to_s + ">"
  else
    return markdown
  end
end

puts markdownparser(" smaller header")

简单的markdown解析器函数:

Headers 由 (1-6) hashes 后跟 [= 指定62=],后面是text。哈希数决定了 HTML 输出的 header 级别

如何进一步降低时间复杂度?

非常感谢

用标准方法替换显式循环

你在循环中做很多事情,所以我会避免这种情况,除非你有一个非常具体的用例不使用 Ruby 的优化方法。有内置的核心或标准库方法来执行诸如计算出现次数或替换文本之类的事情,因此我会尽可能使用它们。如果速度真的很重要,我也会选择字符串插值而不是与 String#+ 连接,其中每个 sub-expression 创建一个新的中间字符串。

一种实现方法如下:

md_str = <<~'EOF'
  # Header 1
  Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor  
  incidunt ut labore et dolore magna aliqua.

  ## Header 2
  Etiam habebis sem dicantur magna mollis euismod.

  ####### Invalid Header with 7 "#" Characters
  ^^^^^^^ Too many characters to be valid.
EOF

# helper method to count header characters
def header_level str
  str&.count "#"
end

# replace markdown headers with html headers;
# escape hash in regex so it won't be treated as interpolation;
# block form required for proper handling of match variables
md_str.gsub!(/^(\#{1,6})\s+(.*)$/) { |_| "<h#{header_level }>#{}</h>" }

puts md_str

这利用 String#count to count the number of # characters in your string, rather than having to loop through it. String#gsub 仅在以 header 字符开头的行上调用 #header_level。

注意事项

  1. 显然这不处理“带下划线”的 header,但这不是您问题的一部分。
  2. Slurping 文件与 line-at-a-time 处理涉及各种 trade-offs,但没有上下文行很难进行复杂的解析。
  3. 无法替代 benchmarking 来测试给定的代码是否真的更快。
  4. 这种方法本身并没有消除迭代。它只是将迭代卸载到尽可能以 C 速度 运行 的方法。