所以我正在为ruby dev bootcamp做准备工作,需要创建一个可以大写游戏的程序。我当前的代码使用#capitalize!
但是当字符串中包含一个数字时,它将被省略。
words = title.split(' ')
words.map! do |word|
if %w(a aboard about above absent across after against along alongside amid amidst among amongst an and around as aslant astride at
athwart atop barring before behind below beneath beside besides between beyond but by despite down during except for from in inside
into like mid minus near next nor notwithstanding of off on onto opposite or out outside over past per plus regarding round save
since so than the through throughout till times to toward towards under underneath unlike until up upon via vs. when with within
without worth yet ).include?(word) && word != words[0]
word
else
word.capitalize!
end
所以输入what I wish I knew when I was 20
后我得What I Wish I Knew When I Was
有什么建议吗?
答案 0 :(得分:5)
使用capitalize
代替capitalize!
。
顺便说一句,如果你word != words[0]
的意图是要将列表中的任何单词保留为大写,如果它不是第一个单词,那么你错了。它不像那样工作。原因留给你作为家庭作业。
答案 1 :(得分:0)
只需将word.capitalize!
更改为word.capitalize! || word
"20".capitalize! #=> nil
"20".capitalize! || "20" #=> 20