Skip to content

Instantly share code, notes, and snippets.

@jonelf
Last active December 27, 2015 08:19
Show Gist options
  • Save jonelf/7295851 to your computer and use it in GitHub Desktop.
Save jonelf/7295851 to your computer and use it in GitHub Desktop.
Start_tags = {"*" => :emphasis, "{" => :footnote}
End_tags = {emphasis: "*", footnote: "}"}
Tags = Start_tags.keys.join
def split_by_paragraph(text, &block)
mode = Start_tags[text[0]] || :normal
if mode == :normal
index = text[1..-1].index /[#{Tags}]/
if index.nil?
yield ({:type => mode, :content => text})
else
yield ({type: mode, content: text[0..index]})
split_by_paragraph(text[index+1..-1], &block)
end
else
index = text[1..-1].index End_tags[mode]
raise 'Missing closing' + End_tags[mode] + ' character.' if index.nil?
yield ({type: mode, content: text[1..index]})
split_by_paragraph(text[index+2..-1], &block) if index < text.length
end
end
text = "Normal text. *emphasised* {footnote} Test end."
paragraphs = []
split_by_paragraph(text) {|p| paragraphs << p}
p paragraphs
@jonelf
Copy link
Author

jonelf commented Nov 3, 2013

Result:

[{:type=>:normal, :content=>"Normal text. "},
{:type=>:emphasis, :content=>"emphasised"},
{:type=>:normal, :content=>" "},
{:type=>:footnote, :content=>"footnote"},
{:type=>:normal, :content=>" Test end."}]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment