Forum: Ruby How to capitalize first word of a string?

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.
F04a22457fcbfee2afc77e77482abe08?d=identicon&s=25 Rails List (railslist)
on 2009-06-04 21:41
I have a string that I would like to capitalize and add bold html tag to
the first word only.  How do i do it?.  Do I have to split first and
then "upcase!" it then join again.  Not sure how to do it.  any help is
much appreciated. thanks
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-06-04 22:50
(Received via mailing list)
On 04.06.2009 21:41, Rails List wrote:
> I have a string that I would like to capitalize and add bold html tag to
> the first word only.  How do i do it?.  Do I have to split first and
> then "upcase!" it then join again.  Not sure how to do it.  any help is
> much appreciated. thanks

Do you mean

irb(main):003:0> words = "foo bar baz"
=> "foo bar baz"
irb(main):004:0> words.sub(/\w+/) {|m| "<b>#{m.upcase}</b>"}
=> "<b>FOO</b> bar baz"
irb(main):005:0> words.sub(/\w+/) {|m| "<b>#{m.capitalize}</b>"}
=> "<b>Foo</b> bar baz"
irb(main):006:0>

Kind regards

  robert
Fbb4d027695dfdf76bf448b15d7e306a?d=identicon&s=25 matt neuburg (Guest)
on 2009-06-04 22:51
(Received via mailing list)
Rails List <balaa_uk@yahoo.com> wrote:

> I have a string that I would like to capitalize and add bold html tag to
> the first word only.  How do i do it?.  Do I have to split first and
> then "upcase!" it then join again.  Not sure how to do it.  any help is
> much appreciated. thanks

Sure, that's a good way. A little-known feature of "split" is the
"limit" parameter, so you can split off just the first word without
affecting anything else:

arr = s.split(" ", 2)
arr[0].upcase! # and anything else you feel like
s = arr.join(" ")

m.
4828d528e2e46f7c8160c336eb332836?d=identicon&s=25 Robert Heiler (shevegen)
on 2009-06-05 00:54
>  A little-known feature of "split" is the "limit" parameter

Didn't know that one. :)
F04a22457fcbfee2afc77e77482abe08?d=identicon&s=25 Rails List (railslist)
on 2009-06-05 19:37
Marc Heiler wrote:
>>  A little-known feature of "split" is the "limit" parameter
>
> Didn't know that one. :)

Thanks for taking time to reply. much appreciated.

Is there any way, I can capitalize the string and simultaneously convert
the first word to bold.

right now, i am splitting

str.split(/\s+/).each{ |word| word.capitalize! } then upcase of str[0]
and then str.each{ |word| }.join(' ')
This topic is locked and can not be replied to.