Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby -- capitalize first letter of every sentence in a paragraph

Tags:

string

ruby

Using Ruby language, I would like to capitalize the first letter of every sentence, and also get rid of any space before the period at the end of every sentence. Nothing else should change.

Input =  "this is the First Sentence . this is the Second Sentence ."    
Output =  "This is the First Sentence. This is the Second Sentence."

Thank you folks.

like image 588
roytony Avatar asked Oct 16 '25 20:10

roytony


2 Answers

Using regular expression (String#gsub):

Input =  "this is the First Sentence . this is the Second Sentence ."    
Input.gsub(/[a-z][^.?!]*/) { |match| match[0].upcase + match[1..-1].rstrip }
# => "This is the First Sentence. This is the Second Sentence."

Input.gsub(/([a-z])([^.?!]*)/) { $1.upcase + $2.rstrip }  # Using capturing group
# => "This is the First Sentence. This is the Second Sentence."

I assumed the setence ends with ., ?, !.

UPDATE

input = "TESTest me is agreat. testme 5 is awesome"
input.gsub(/([a-z])((?:[^.?!]|\.(?=[a-z]))*)/i) { $1.upcase + $2.rstrip }
# => "TESTest me is agreat. Testme 5 is awesome"

input = "I'm headed to stackoverflow.com"
input.gsub(/([a-z])((?:[^.?!]|\.(?=[a-z]))*)/i) { $1.upcase + $2.rstrip }
# => "I'm headed to stackoverflow.com"
like image 189
falsetru Avatar answered Oct 18 '25 16:10

falsetru


Input.split('.').map(&:strip).map { |s|
  s[0].upcase + s[1..-1] + '.'
}.join(' ')
=> "This is the First Sentence. This is the Second Sentence."

My second approach is cleaner but produces a slightly different output:

Input.split('.').map(&:strip).map(&:capitalize).join('. ') + '.'
=> "This is the first sentence. This is the second sentence."

I'm not sure if you're fine with it.

like image 36
Jun Zhou Avatar answered Oct 18 '25 17:10

Jun Zhou