8. How do I .capatalize!?


#1

How would I capatalize the user's input after the changes made?
I tried this code below, but got an error, I also tried to add the code in the puts string, in the { } but error.


print "Say something?"
user_input = gets.chomp
user_input.downcase!

if user_input.include? "s"
    user_input.gsub!(/s/, "th")
    user_input.capatalize!
    puts "Daffy Duck says, #{user_input}"
else
    print "Daffy Duck says, #{user_input}"
end


#2

While it is not asked for in the lesson, this is a good question from a practice point of view.

Say we have a phrase,

atoz = "a quick brown fox jumps over the lazy dog"

capitalize! will only capitalize the first letter of the phrase, not of each word in the phrase. To capitalize all first letters we need to split the words into an array, then iterate over the array.

words = atoz.split(" ")
words.each { |word| word.capitalize! }
caps = words.join(' ')
print caps    # A Quick Brown Fox Jumps Over The Lazy Dog

#3

What about just the first letter of the beginning of the sentence?


#4
sentence = "a quick brown fox jumps over the lazy dog."

sentence.capitalize!

print sentence    # A quick brown fox jumps over the lazy dog.

Here is the above word capitalize program, refactored:

def all_caps(phrase)
    cap = lambda { |_| _.capitalize! }
    return phrase.split(" ").each(&cap).join(' ')
end

atoz = "a quick brown fox jumps over the lazy dog"
print "#{all_caps(atoz)}"

#6