所以我是Ruby的新手,我的任务是手动将字符串转换为title-case。我终于能够创建一种我相信能够满足我的任务要求的方法(它不是很灵活,但它可以做到),但是我遇到了最后一个障碍。我似乎不能将最后一个数组连接到一个字符串中。我的代码和Rspec错误如下。我认为我必须在某个地方使用.join(“"),但我不确定确切的语法。提前感谢您的帮助!
我的代码:
class Title
attr_accessor :string
def initialize(string)
@string = string
end
def fix
string.split(" ").each_with_index do |value, index|
if index >= 2 && value.length <= 3
value.downcase!
else
value.capitalize!
end
end
end
endRspec:
expected: "The Great Gatsby"
got: ["The", "Great", "Gatsby"]
(compared using ==)
exercise_spec.rb:6:in `block (3 levels) in <top (required)>'再一次:
expected: "Little Red Riding Hood"
got: ["Little", "Red", "Riding", "Hood"]
(compared using ==)
exercise_spec.rb:9:in `block (3 levels) in <top (required)>'再一次:
expected: "The Lord of the Rings"
got: ["The", "Lord", "of", "the", "Rings"]
(compared using ==)
exercise_spec.rb:12:in `block (3 levels) in <top (required)>'再一次:
expected: "The Sword and the Stone"
got: ["The", "Sword", "and", "the", "Stone"]
(compared using ==)
exercise_spec.rb:17:in `block (3 levels) in <top (required)>'发布于 2015-07-09 04:05:02
快速解决方案:
def fix
string.split(" ").each_with_index do |value, index|
if index >= 2 && value.length <= 3
value.downcase!
else
value.capitalize!
end
value
end.join(" ")
end如果你想用红宝石的方式去做:
def fix
string.split(" ").map(&:capitalize).join(" ")
end发布于 2015-07-09 04:44:12
ActiveSupport提供了一个名为titleize的方法,它可以完成您所描述的操作:
>> "the great gatsby".titleize
=> "The Great Gatsby"
>> "little red riding hood".titleize
=> "Little Red Riding Hood"
>> "the lord of the rings".titleize
=> "The Lord Of The Rings"来源:http://apidock.com/rails/ActiveSupport/Inflector/titleize
发布于 2015-07-09 04:55:49
要提供替代解决方案,请执行以下操作:
def fix
string.downcase.gsub(/^\S+|(\S{4,})/, &:capitalize)
end这只是将出现在字符串开头或长度为4+个字符的每个单词替换为其大写形式。
https://stackoverflow.com/questions/31302550
复制相似问题