[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

How to capitalize first word of a string?

Rails List

6/4/2009 7:42:00 PM

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
--
Posted via http://www.ruby-....

4 Answers

Robert Klemme

6/4/2009 8:46:00 PM

0

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

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestprac...

matt

6/4/2009 8:48:00 PM

0

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.
--
matt neuburg, phd = matt@tidbits.com, http://www.tidbits...
Leopard - http://www.takecontrolbooks.com/leopard-custom...
AppleScript - http://www.amazon.com/gp/product/...
Read TidBITS! It's free and smart. http://www.t...

Marc Heiler

6/4/2009 10:55:00 PM

0

> A little-known feature of "split" is the "limit" parameter

Didn't know that one. :)

--
Posted via http://www.ruby-....

Rails List

6/5/2009 5:37:00 PM

0

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(' ')
--
Posted via http://www.ruby-....