From: Daniel N Date: 2007-10-04T13:35:07+09:00 Subject: Re: opinion on a simple method ------=_Part_14851_16787274.1191472506846 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On 10/4/07, Lloyd Linklater wrote: > > I am trying to find the better way to do things ruby style. I needed to > make a method that would read in a file of movie titles and capitalize > each word. > > "this is a string".capitalize just gets the first word, so I did this: > > File.open('\movies.txt') do |f| > while line = f.gets > s = "" > line.split(/ /).each {|one_word| s += one_word.capitalize + ' '} > puts s.chop > end > end > > Is there a cleaner or more "rubyish" way to do this? > -- In rails, activesupport there is the titlize method # Capitalizes all the words and replaces some characters in the string to create # a nicer looking title. Titleize is meant for creating pretty output. It is not # used in the Rails internals. # # titleize is also aliased as as titlecase # # Examples # "man from the boondocks".titleize #=> "Man From The Boondocks" # "x-men: the last stand".titleize #=> "X Men: The Last Stand" def titleize(word) humanize(underscore(word)).gsub(/\b([a-z])/) { $1.capitalize } end So for your file you could use File.open( '\movies.txt') do |f| f.each_line do |line| puts line.gsub(/\b(a-z])/){ $1.capitalize } end end Or if you don't mind printing the whole thing out in one go File.open( \'movies.txt') do |f| puts f.read.gsub(/\b([a-z]/){ $1.capitalize } end HTH Daniel ------=_Part_14851_16787274.1191472506846--