Михаил обнови решението на 23.11.2011 23:49 (преди около 13 години)
+# пак почнах, два часа преди крайния срок..., но тестове без #специални
+# символи и списъци и празни редове трябва да ги мине без #проблем
+#Сложил съм някои методи и редове в коментар, понеже нямах време
+#да ги оптимизирам, за да мина условията
+class Formatter
+ def initialize unformatted_string
+ @hash = {:p => "</p>", :h1 => "</h1>", :h2 => "</h2>", :h3 => "</h3>",
+ :h4 => "</h4>", :ul => "</ul>", :li => "</li>", :ol => "\n</ol>", :a => "</a>",
+ :blockquote => "</p></blockquote>", :code => "</code></pre>"}
+ # @last_line = ""
+ # @last_tag = :nothing
+ @original = unformatted_string
+ @formatted = unformatted_string.lines.map{|line|
+ @last_line = handle_line(line)
+ @last_line}.join
+ @formatted+=@hash[@last_tag].to_s
+ end
+ def to_html
+ puts @formatted
+ end
+ def to_s
+ to_html
+ end
+# def inspect
+# puts @original
+# end
+ def handle_line line
+ if line.match(/^\#{1,4} .*/)
+ handle_title line
+ elsif line.match(/^ {4}[^ ].*/)
+ handle_code line
+ elsif line.match(/^> .*/)
+ handle_quote line
+ # elsif line.match(/^[0-9]. .*/)
+ # handle_ordered_list line
+ # elsif line.match(/^\* .*/)
+# handle_unordered_list line
+ else handle_paragraph line
+ end
+ end
+ def handle_ordered_list line
+ unless @last_tag.eql? :ol
+ closepreviousline
+ line.sub!(/^[0-9]. */, "<ol>\n <li>")
+ @last_tag = :ol
+ end
+ line.sub!(/^[0-9]. */, " <li>")
+ line.sub!(/ *$/, "</li>")
+ end
+ def handle_code line
+ unless @last_tag.eql? :code
+ closepreviousline
+ @last_tag = :code
+ line.sub!(/^ {4}/, "<pre><code>")
+ else
+ line.sub!(/^ {4}/, "")
+ end
+ end
+ def handle_quote line
+ unless @last_tag.eql? :blockquote
+ closepreviousline
+ line.sub!(/^> */, "<blockquote><p>")
+ @last_tag = :blockquote
+ end
+ line.sub!(/^> */, "")
+ line.sub!(/ *$/, "")
+ end
+ def handle_title line
+ closepreviousline
+ @last_tag = :h1
+ m = line.match(/^(\#{1,4})/)
+ line.sub!(/^\#{1,4} */, "<h"+m[1].size.to_s+">")
+ line.sub!(/ *$/, "</h"+m[1].size.to_s+">")
+ end
+ def handle_paragraph line
+ unless @last_tag.eql? :p
+ closepreviousline
+ line.sub!(/^ */, "<p>")
+ @last_tag = :p
+ end
+ line.sub!(/^ */, "")
+ line.sub!(/ *$/, "")
+ end
+ def closepreviousline
+ if @last_tag.eql? :p or @last_tag.eql? :blockquote
+ or @last_tag.eql? :code or @last_tag.eql? :ol
+ @last_line.sub!(/$/, @hash[@last_tag].to_s)
+ end
+ end
+# def format_line line
+# line.gsub!(/"/, """)
+# line.gsub!(/&/, "&")
+# end
+end
+
+#formatter = Formatter.new " asdasdasd
+### asdasdasdasd
+#sdahashakjsh
+#1. raboti
+#2. li
+#3. tova?
+#> ctataata
+### zaglavie?
+#> produljava
+#sledva paragraph
+# i o6te ot nego
+# dali code
+# raboti
+# ASDASD
+# coda"
+#formatter.to_s