Daniel10
(Daniel)
3 November 2002 07:18
1
Hi All,
I’d like to capitalize every word in a string.
I was hoping this expression would do it:
newstr = str.gsub(/\b(\s)?([a-z])/,’\1\2’.upcase)
but it turns out that as \2 is not evaluated right away, the .upcase has
no effect. Suggestions?
db
···
–
A.D. 1844: Samuel Morse invents Morse code. Cryptography export
restrictions prevent the telegraph’s use outside the U.S. and Canada.
Daniel10
(Daniel)
3 November 2002 07:32
2
btw, I have this solution, but I’d like to know the thory why my other
solution didn’t work
bits = str.split(‘\s’)
for b in bits
b.capitalize!
end
str = bits.join(’ ')
···
On Sun, Nov 03, 2002 at 04:18:20PM +0900, Daniel Bretoi wrote:
Hi All,
I’d like to capitalize every word in a string.
I was hoping this expression would do it:
newstr = str.gsub(/\b(\s)?([a-z])/,‘\1\2’.upcase)
but it turns out that as \2 is not evaluated right away, the .upcase has
no effect. Suggestions?
db
A.D. 1844: Samuel Morse invents Morse code. Cryptography export
restrictions prevent the telegraph’s use outside the U.S. and Canada.
–
A.D. 1844: Samuel Morse invents Morse code. Cryptography export
restrictions prevent the telegraph’s use outside the U.S. and Canada.
HAL_9000
(HAL 9000)
3 November 2002 07:53
3
Hi All,
I’d like to capitalize every word in a string.
One way:
str.split.map {|x| x.capitalize}.join(" ")
but you may not be happy with the way it treats
spaces and such.
I was hoping this expression would do it:
newstr = str.gsub(/\b(\s)?([a-z])/,‘\1\2’.upcase)
but it turns out that as \2 is not evaluated right away, the .upcase has
no effect. Suggestions?
Maybe break it up.
str = “what hath god wrought?”
newstr = “”
str.scan(/(\w)(\w+)(\W)*/) {|x,y,z| newstr << x.upcase << y << z}
p newstr # “What Hath God Wrought?”
This works for me. Depends on your data.
Hal
···
----- Original Message -----
From: “Daniel Bretoi” lists@debonair.net
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Sunday, November 03, 2002 1:18 AM
Subject: substitution problem
ts1
(ts)
3 November 2002 10:40
4
btw, I have this solution, but I'd like to know the thory why my other
solution didn't work
When you write
newstr = str.gsub(/\b(\s)?([a-z])/,'\1\2'.upcase)
ruby call the method #upcase for the string '\1\2' and the result is given
as the second argument of #gsub
'\1\2'.upcase is the same than '\1\2'
Guy Decoux
I’d like to capitalize every word in a string.
One way:
str.split.map {|x| x.capitalize}.join(" ")
but you may not be happy with the way it treats
spaces and such.
Similar to your second example and preserving spaces:
str = “the quick brown fox, jumped over the lazy dog”
str.scan(/(\w+)(\W+)*/).flatten.map {|x| x.capitalize unless x.nil?}.join
This works for me. Depends on your data.
Ditto.
Massimiliano
···
On Sun, Nov 03, 2002 at 04:53:30PM +0900, Hal E. Fulton wrote: