Topic: Capitalize every word?

Simple one for ya guys...
If I have a sentence and want to capitalize every word, what method would I enact on it?
The only thing I can find is str.upcase, but I don't want the whole thing in caps.. but
"this is a sentence" to "This Is A Sentence"

Thanks

Re: Capitalize every word?

okay I can do this in ruby you'll need to tailor it your self.

a = "this is a sentence"
a = a.split #turn it into an array

a.each {|x| print x.capitalize, " "}


there might be a better way of doing it but it works for me.

Last edited by BasicMind (2006-11-21 10:02:04)

--

Re: Capitalize every word?

Hmm..
I was thinking along the same lines, but with that I'm still only getting it to capitalize the first word :-/ at least in the console.

Re: Capitalize every word?

hmmm, I just did it in my console and it works

--

Re: Capitalize every word?

be sure to reasign the var otherwise it will only capitalize the first part.
ie
a = a.split

a.split simply wont do it

or try

a = a.split.each{|x| print x.capitalize, " ")

Last edited by BasicMind (2006-11-21 10:34:55)

--

Re: Capitalize every word?

Got it working, thanks!
I ended up with

  a = a.split.each { |x| print x.capitalize!, " "}.join(" ")

Last edited by pjleonhardt (2006-11-21 10:57:08)

Re: Capitalize every word?

titleize ?

Re: Capitalize every word?

rarg!
I forgot that this is Rails, where there is a made up word to do exactly what you're trying to do.

smile

Re: Capitalize every word?

just for clearification, if you would not use the titleize thingie ..

there is no need to split the string to an array

string.each(" ") {|word| word.capitalize }

Re: Capitalize every word?

Cool, I never knew about splitting a string by passing an argument to the each method. That's really useful.

Unfortunately, the result of the block isn't collected anywhere, so it won't work in this case. Still cool though.

Railscasts - Free Ruby on Rails Screencasts