Forum: Ruby on Rails capitalizing words

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C56c078159148c1e3ac494ad8a7a74e0?d=identicon&s=25 raghus (Guest)
on 2007-07-04 00:04
(Received via mailing list)
I am trying to write a function that converts something like "It's a
dog's life" to "It's A Dog's Life". I am doing this with string.gsub(/
\b\w/) {$&.upcase} but this gives me "It'S A Dog'S Life" - how can I
tell the regexp to ignore apostrophes when looking for a new word to
capitalize?
28df70e0163c43e9f3b7ede657a17853?d=identicon&s=25 Scott Thorpe (sthorpe)
on 2007-07-04 00:08
(Received via mailing list)
item.capitalize ??

--Scott T.
28df70e0163c43e9f3b7ede657a17853?d=identicon&s=25 Scott Thorpe (sthorpe)
on 2007-07-04 00:10
(Received via mailing list)
3299251223f55753ec84719de39e6e53?d=identicon&s=25 Jon Garvin (Guest)
on 2007-07-04 01:11
(Received via mailing list)
raghus wrote:
> I am trying to write a function that converts something like "It's a
> dog's life" to "It's A Dog's Life". I am doing this with string.gsub(/
> \b\w/) {$&.upcase} but this gives me "It'S A Dog'S Life" - how can I
> tell the regexp to ignore apostrophes when looking for a new word to
> capitalize?
>
>
string.titleize will give you the same result you're getting.  Doesn't
help you at all with this problem, but, just for future reference.

But, back to the problem you're having.  This seems to do the trick.

string.gsub(/(^|[^\w'])([\w'])/) {$&.upcase}

--
http://www.5valleys.com/
C56c078159148c1e3ac494ad8a7a74e0?d=identicon&s=25 raghus (Guest)
on 2007-07-04 05:54
(Received via mailing list)
Jon - ok that worked. Thank you. Thanks for the titleize tip as well.
Scott - mystr.capitalize will capitalize just the first character - so
I'd end up with "It's a dog's life" rather than "It's A Dog's Life"
This topic is locked and can not be replied to.