Ruby 2.3.3 中的手动标题化
Manual Titleize in Ruby 2.3.3
我正在尝试将所有字符串输入大写,不包括 "Of"、"The" 或 "And" 等小词。
我不明白为什么代码不能正常工作。
def titleize(x)
capitalized = x.split.each do |i|
if i.length >= 2
if i == "of" || "the" || "and"
next
else
i.capitalize!
end
else
next
end
end
capitalized.join(' ')
end
这是我的 Rspec 输出:
失败:
1) Simon says titleize capitalizes a word
Failure/Error: expect(titleize("jaws")).to eq("Jaws")
expected: "Jaws"
got: "jaws"
(compared using ==)
您有一个 string literal in condition
警告:
if i == "of" || "the" || "and"
您正在尝试将 i
与 of
或 the
或 and
进行比较,但在第一次尝试后,您没有将左值传递给比较,尝试:
if i == "of" || i == "the" || i == "and"
更惯用的 Ruby 是使用 include?
if ['of', 'the', 'and'].include?(i)
这样至少你得到了Jaws
您的实际方法对字符串 war and peace
不起作用的原因是,如果传递的单词的长度小于或等于 2,那么它将执行 next
,所以,它只会大写 peace
.
这个词
我正在尝试将所有字符串输入大写,不包括 "Of"、"The" 或 "And" 等小词。
我不明白为什么代码不能正常工作。
def titleize(x)
capitalized = x.split.each do |i|
if i.length >= 2
if i == "of" || "the" || "and"
next
else
i.capitalize!
end
else
next
end
end
capitalized.join(' ')
end
这是我的 Rspec 输出:
失败:
1) Simon says titleize capitalizes a word
Failure/Error: expect(titleize("jaws")).to eq("Jaws")
expected: "Jaws"
got: "jaws"
(compared using ==)
您有一个 string literal in condition
警告:
if i == "of" || "the" || "and"
您正在尝试将 i
与 of
或 the
或 and
进行比较,但在第一次尝试后,您没有将左值传递给比较,尝试:
if i == "of" || i == "the" || i == "and"
更惯用的 Ruby 是使用 include?
if ['of', 'the', 'and'].include?(i)
这样至少你得到了Jaws
您的实际方法对字符串 war and peace
不起作用的原因是,如果传递的单词的长度小于或等于 2,那么它将执行 next
,所以,它只会大写 peace
.