我应该:
- 将字符串的第一个字母大写。
the
除冠词 ( ,a
,an
)、连词 (and
) 和介词 ( ) 之外的每个单词都大写in
。- 大写
i
(如"I am male."
)。 - 指定字符串的第一个单词(我实际上不知道这意味着什么。我正在尝试运行规范文件来测试其他函数)。
这是我的代码:
class Book
def initialize(string)
title(string)
end
def title(string)
arts_conjs_preps = %w{ a an the and
but or nor for
yet so although
because since
unless despite
in to
}
array = string.downcase.split
array.each do |word|
if (word == array[0] || word == "i") then word = word.capitalize
if arts_conjs_preps !include?(word) then word = word.capitalize
end
puts array.join(' ')
end
end
puts Book.new("inferno")
Ruby 说我搞砸了:
puts Book.new("inferno") <--(right after the last line of code)
我得到与此测试代码完全相同的错误消息:
def title(string)
array = string.downcase.split
array.each do |word|
if word == array[0] then word = word.capitalize
end
array.join(' ')
end
puts title("dante's inferno")
关于此特定语法错误的唯一其他 Stack Overflow 线程不建议将尾随或丢失end
s 或.
s 作为问题的根源。最后一条评论建议删除并重新创建 gemset,这听起来很可怕。而且我不知道该怎么做。
有什么想法吗?简单的解决方案?有帮助的资源?
解决方案
class Book
def initialize(string)
title(string)
end
def title(string)
arts_conjs_preps = %w{ a an the and
but or nor for
yet so although
because since
unless despite
of in to
}
array = string.downcase.split
title = array.map do |word|
if (word == array[0] || word == "i") || !arts_conjs_preps.include?(word)
word = word.capitalize
else
word
end
end
puts title.join(' ')
end
end
Book.new("dante's the inferno")