So it's apparent this question has been asked before, but what I'm actually asking is specific to the code I am writing. Basically I'm capitalizing the words (titleizing). My method is not optimized, and it does go in circles so just bear with me. I can't seem to recapitalize the first word of the title once I made it lowercased again. I have written comments in the code, so you can just breeze through it without analyzing the entire thing. I'm not asking you to write a new code because I can just google that. I'm more interested in why my solutions aren't working..
input: "the hamster and the mouse"
output: "the Hamster and the Mouse"
WHAT I WANT: "The Hamster and the Mouse"
class String
def titleize
#regex reads: either beginning of string or whitespace followed by alpha
self.gsub(/(\A|\s)[a-z]/) do |letter|
letter.upcase!
end
end
end
class Book
attr_accessor :title
def title=(title)
@title = title.titleize #makes every word capitalized
small_words = %w[In The And A An Of]
words = @title.split(" ")
#makes all the "small_words" uncapitalized again
words.each do |word|
if small_words.include?(word)
word.downcase!
end
end
words[0][0].upcase! #doesnt work
@title = words.join(" ")
#NEED TO MAKE FIRST WORD CAPITALIZED EVEN IF ITS A "small_word"
@title[0].upcase! #also doesnt work
end
end