Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly format strings like 'mccdougal' to 'McDougal'

What Ruby or Rails DSL will format a string "mccdougal" to "McDougal", and at the same time leave the string "McDougal" as is?

Passing titleize to "McDougal" results in the following:

"McDougal".titleize # => "Mc Dougal"
like image 899
robskrob Avatar asked Feb 29 '16 21:02

robskrob


2 Answers

There isn't a Rails helper to my knowledge that can handle this case. It's a non-standard edge case which needs special handling. You could create a custom string inflection, however. You could drop this bit of code in an initializer:

ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.human /mcdougal/, 'McDougal'
end

And then when you call "mcdougal".humanize, you'll get "McDougal"

like image 69
Josh Deeden Avatar answered Oct 02 '22 18:10

Josh Deeden


You aren't going to find something that correctly formats a name like that. The reason is because the reason that the M and D in McDougal are capitalized is an arbitrary regional thing. The only way that I can think of doing something like that is with a lookup table. I would say that the best you'll get programatically is "mcdougal".capitalize => "Mcdougal". I would argue that you can't and shouldn't guess regional capitalizations.

If However you are making an app for the Irish however, and it absolutely needs to be done. I would make a lookup table to solve the problem. It's tedious, but you'll find a finite amount of cases.

like image 29
unflores Avatar answered Oct 02 '22 19:10

unflores