How to capitalize first word of a string?

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

On 04.06.2009 21:41, Rails L. 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| “#{m.upcase}”}
=> “FOO bar baz”
irb(main):005:0> words.sub(/\w+/) {|m| “#{m.capitalize}”}
=> “Foo bar baz”
irb(main):006:0>

Kind regards

robert

Rails L. [email protected] 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.

A little-known feature of “split” is the “limit” parameter

Didn’t know that one. :slight_smile:

Marc H. wrote:

A little-known feature of “split” is the “limit” parameter

Didn’t know that one. :slight_smile:

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