Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

RUBY | Find a way to find an exception on the same word to capitalize

def titleize(string)

nocaps = ["the","and"]
puts string.split(" ").map { |word| nocaps.include?(word) ? word : word.capitalize }.join(" ")

end

titleize("the bridge over the river kwai")
------------------------------------------------------------------------------------------
######Render => "the Bridge Over the River Kwai"

######Expected rendering => "The Bridge Over the River Kwai"

Hello i present you my piece of code, the rendering gives "the Bridge Over the River Kwai" While I would like "The Bridge Over the River Kwai" So I would like to find a way to find an exception on the same word.

question from:https://stackoverflow.com/questions/65920306/how-to-make-a-string-title-case-in-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code, but always capitalise the first letter, using each_with_index to get the position in the array:

def titleize(string)
  nocaps = ["the","and"]
  string.split(" ").each_with_index.map { |word, i| i.positive? && nocaps.include?(word) ? word : word.capitalize }.join(" ")
end

titleize("the bridge over the river kwai")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...