Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

titleize a hyphenated name

Rails' titleize method removes hyphens, and Ruby's capitalize method does not capitalize the word that comes after a hyphen. I want something like the following:

"mary-joe spencer-moore" => "Mary-Joe Spencer-Moore"

"mary-louise o'donnell" => "Mary-Louise O'Donnell"
like image 524
kangkyu Avatar asked Apr 21 '15 23:04

kangkyu


2 Answers

Check Titelize implementation and from it you can get:

"mary-joe spencer-moore".humanize.gsub(/\b('?[a-z])/) { $1.capitalize }

will give you => "Mary-Joe Spencer-Moore"

and you can write a function for it in string class, Add to intalizers:

class String
  def my_titleize
    humanize.gsub(/\b('?[a-z])/) { $1.capitalize }
  end
end

and then from your code:

"mary-joe spencer-moore".my_titleize
like image 58
mohamed-ibrahim Avatar answered Sep 30 '22 19:09

mohamed-ibrahim


You could also get the desired result by splitting up your string and titleizing the sections separately:

"mary-louise o'donnell".split('-').map(&:titleize).join('-')
like image 30
gabeodess Avatar answered Sep 30 '22 20:09

gabeodess