From: Josh Cheek Date: 2011-09-30T09:04:50+09:00 Subject: Re: simple program, need help --20cf307cfe9ca6af2204ae1d5f5d Content-Type: text/plain; charset=ISO-8859-1 On Thu, Sep 29, 2011 at 5:19 PM, Trevor Harker wrote: > File attached. > > I need some help with a simple program to capitalize the first letter of > each word in a sentence. > > I'm not sure if I should be using class Array, but I dont think that's > the problem. > > Here's the code: > > class Array > def title_format (title) > puts title.split(" ").each{|element| print > element.capitalize!}.join(" ") > return title_format > end > end > > puts "Please type the sentence you want to have put in \"Title Format\"" > > title = gets.chomp > > title.title_format > > Help would be greatly appreciated. This is the error i get: > > sentence_caps.rb:18: undefined method `title_format' for "please help me > with my program":String (NoMethodError) > > Thanks > > Attachments: > http://www.ruby-forum.com/attachment/6641/sentence_caps.rb > > > -- > Posted via http://www.ruby-forum.com/. > > What Hassan said, but something to consider is that this will change your string in ways you don't necessarily want. class String def title_format self.split.each{|element| element.capitalize! }.join(" ") end end string = "unexpected\n \tWhitespace" string.title_format # => "Unexpected Whitespace" # instead, I'd do it like this, which substitutes each run of non-whitespace characters # and substitutes them with their capitalized version class String def title_format gsub(/\S+/) { |word| word.capitalize } # which can actually be shortened to: gsub(/\S+/, &:capitalize) end end string.title_format # => "Unexpected\n \tWhitespace" --20cf307cfe9ca6af2204ae1d5f5d--