The title pretty much explains it. I'm writing a blog engine for myself with Ruby 1.9.3 and Rails 3.2.2 and I need to be able to grab the first paragraph from a post (which is stored as a text unit in the DB) to use as a post summary for the front page. What's the simplest way of doing this?
Google revealed very little on this issue; it doesn't seem like a common need.
The answer becomes rather obvious once you start thinking what exactly defines "a paragraph" in your world.
If it is the first list of characters followd by two newline characters? Something like
str.split("\n\n", 2)[0]
could work.
If you have HTML and your paragraphs are defined by <p>
tags, use nokogiri like
Nokogiri::HTML.parse(input_string).css('p').first.text
But agin, it all depends on how you define your paragraph. And stuff like this most often solves itself once you start thinking about what exactly you want to have, i.e. how to transform the input data to output data in an abstract way. The required algorithm comes naturally from these steps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With