On Thu, Sep 29, 2011 at 3:19 PM, Trevor Harker [email protected] wrote:
I need some help with a simple program to capitalize the first letter of
each word in a sentence.
class Array
def title_format (title)
puts title.split(" “).each{|element| print
element.capitalize!}.join(” ")
return title_format
end
end
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)
Which is exactly right – ‘title’ is a string and there’s no such
method.
But you can add one:
class String
def title_format
self.split.each{|element| element.capitalize! }.join(" ")
end
end
puts “what the heck”.title_format #=> What The Heck
You definitely don’t want the print and puts inside your method,
and in your example you’re trying to return the method itself, which
is bound to end badly
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”