The issue you're having in the second example is that Array#each
returns the enumerable on which .each
was called, so in this case you're getting the result from book_title.split(" ")
(albeit modified by the block). You are assigning this result to the @title
instance variable. Calling join
on an array returns a string, but you're not doing anything with that string except allocating it. If you'd like to assign it to the title variable, you need to do @title = @title.join(" ")
. Same with capitalize
.
Ruby: Method within a class refuses to be modified over multiple lines
-
28-06-2022 - |
質問
I am currently doing an rspec ruby tutorial. One of the problems requires me to write a book_title program that utilizes some of the capitalization rules in English. The tests are extremely long but to give you a few ideas of what it is asking for I've included the first last tests below:
require 'book'
describe Book do
before do
@book = Book.new
end
describe 'title' do
it 'should capitalize the first letter' do
@book.title = "inferno"
@book.title.should == "Inferno"
end
specify 'the first word' do
@book.title = "the man in the iron mask"
@book.title.should == "The Man in the Iron Mask"
end
end
end
end
My code is:
class Book
attr_accessor :title
def initialize(title = nil)
@title = title
end
def title=(book_title = nil)
stop_words = ["and", "in", "the", "of", "a", "an"]
@title = book_title.split(" ").each{ |word|
unless stop_words.include?(word)
word.capitalize!
end}.join(" ").capitalize
end
end
This issue I am having is with the def title=
method. @title = book_title.split
(...etc) all in one line because when I try and split it up, many of my previous tests fail.
Example of some code I've tried:
@title = book_title.split(" ").each do |word| # attempting to add words to an array
unless stop_words.include?(word) # to capitalize each word
word.capitalize!
end
end
@title.join(" ") # Joining words into one string
@title.capitalize # Capitalizing title's first word
end # to follow the last test
When I try this the tests fail (I am thinking it has to do with calling @title again when I try @title#join and @title#capitalize).
Some other thoughts: I was thinking about just setting the first part (the longest line ending in word.capitalize! end end
to a different variable (maybe book_title or new_title) but I was wondering what the reason for even initializing or using @title would be in the first place.
Any input, as well as edits for cleaner code, would be greatly appreciated
解決