I can't find the solution for this problem, I did a research in order to find the problems and fix them but can't think for any answer yet.
What I want to do is to convert a string into a Title cased string.
For example: "The Lord Of The Rings" > "The Lord of the Rings"
(As you can see, the first word is always capitalized, it doesn't matter if it's an article, but if there are articles words in the string, that should be in downcase, as the example above, and capitalize any other words that aren't).
This is the spec (RSpec) of the exercise I'm trying to solve:
describe "Title" do
describe "fix" do
it "capitalizes the first letter of each word" do
expect( Title.new("the great gatsby").fix ).to eq("The Great Gatsby")
end
it "works for words with mixed cases" do
expect( Title.new("liTTle reD Riding hOOD").fix ).to eq("Little Red Riding Hood")
end
it "downcases articles" do
expect( Title.new("The lord of the rings").fix ).to eq("The Lord of the Rings")
expect( Title.new("The sword And The stone").fix ).to eq("The Sword and the Stone")
expect( Title.new("the portrait of a lady").fix ).to eq("The Portrait of a Lady")
end
it "works for strings with all uppercase characters" do
expect( Title.new("THE SWORD AND THE STONE").fix ).to eq("The Sword and the Stone")
end
end
end
And here's my try, what I have so far:
class Title
def initialize(string)
@string = string
end
def fix
@string.split.each_with_index do |element, index|
if index == 0
p element.capitalize!
elsif index == 1
if element.include?('Is') || element.include?('is')
p element.downcase!
end
end
end
end
end
a = Title.new("this Is The End").fix
p a
Output:
"This"
"is"
=> ["This", "is", "The", "End"]
What I tried to do:
- Create a class named Title and initialize it with a string.
- Create a method called fix that so far, only checks for the index 0
of the
@string.split
with the method.each_with_index
(looping through), and prints theelement.capitalize!
(note the 'bang', that should modify the original string, as you can see it in the output above) - What my code does is to check for the index 1 (second word) and
calls the
.include?('is')
to see if the second word is an article, if it is (with if statements) theelement.downcase!
is called, if not, I could create more checkings for index (but what I realized here is that some strings could be formed by 3 words, others by 5, others by 10, and so on, so my code is not efficient for that, that's a problem I can't solve.
Maybe creating a list of article words and check with the .include? method if there's some word of the list? (I tried this one but the .include? method only accepts a string not an array variable, I tried the join(' ')
method but had no luck).
Thanks a lot! Really!