kangkyu
kangkyu

Reputation: 6090

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"

Upvotes: 17

Views: 5349

Answers (3)

user664833
user664833

Reputation: 19505

 %q%mary-louise o'donnell%.gsub(/\b([a-z])/) { $1.capitalize }
 => "Mary-Louise O'Donnell"

However, if you may have input with unexpected capitalizations (e.g. "MARY-LOUISE O'DONNELL") then you will first need to .downcase; furthermore, if you may have nil values for first and last name, and you're then joining them, then you'll want to .strip:

[first_name, last_name].join(' ').downcase.gsub(/\b([a-z])/) { $1.capitalize }.strip

Upvotes: 1

gabeodess
gabeodess

Reputation: 2222

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('-')

Upvotes: 10

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

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

Upvotes: 26

Related Questions